Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】ステータスバーの通知を端末の再起動後も維持する方法を解説

はじめに

Androidアプリで表示したステータスバーの通知は、端末を再起動すると消えてしまいます。本記事では、BroadcastReceiverRECEIVE_BOOT_COMPLETED権限を組み合わせることで、端末の再起動後もステータスバー通知を自動的に復元・維持する方法を、サンプルコード付きで段階的に解説します。

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

ステップ2:レイアウトファイルを編集する

res/layout/activity_main.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"/>

ステップ3:MainActivityを実装する

src/MainActivity.java に以下のコードを記述します。ここではレイアウトを表示するだけのシンプルな構成です。

package app.tutorialspoint.com.notifyme;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

ステップ4:USBStateReceiver(BroadcastReceiver)を実装する

続いて、通知を表示するためのBroadcastReceiverクラスを作成します。src/USBStateReceiver.java に以下のコードを追加します。

package app.tutorialspoint.com.notifyme;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class USBStateReceiver extends BroadcastReceiver {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";
    boolean connected = true;
    @SuppressLint("UnsafeProtectedBroadcastReceiver")
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, default_notification_channel_id);
        builder.setContentTitle("USB - Notification");
        String action = intent.getAction();
        Log.e("USB", action);
        assert action != null;
        builder.setContentText("Connected");
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        Notification notification = builder.build();
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }
        assert notificationManager != null;
        if (connected) {
            notificationManager.notify(1, notification);
            connected = false;
        } else {
            notificationManager.cancel(1);
            connected = true;
        }
    }
}

このクラスのポイントは以下のとおりです。

  • NotificationCompat.Builderで通知を生成し、NotificationManagerを使って表示しています。
  • Android 8.0(APIレベル26)以降では通知チャンネルの作成が必須のため、SDK_INTを判定してNotificationChannelを生成しています。
  • connectedフラグで接続状態を管理し、通知の表示とキャンセルを切り替えています。

ステップ5:AndroidManifest.xmlを設定する

最後に、AndroidManifest.xml に以下のコードを追加します。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <receiver android:name=".USBStateReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

ここでの重要なポイントは2つあります。

  • android.permission.RECEIVE_BOOT_COMPLETED権限を宣言すること。これにより、端末の起動完了時のブロードキャストを受け取れるようになります。
  • BOOT_COMPLETEDアクションを受け取るreceiverを登録すること。端末の起動が完了するとシステムからこのブロードキャストが送信され、USBStateReceiverのonReceive()が呼び出されて通知が再表示されます。

アプリを実行して動作を確認する

それでは、アプリを実行してみましょう。実機のAndroid端末をパソコンに接続しているものとして説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。実行デバイスとして自分の端末を選択すると、端末にデフォルトの画面が表示されます。

【Android】ステータスバーの通知を端末の再起動後も維持する方法を解説

まとめ

RECEIVE_BOOT_COMPLETED権限と、BOOT_COMPLETEDブロードキャストを受け取るBroadcastReceiverを組み合わせれば、端末を再起動した後でもステータスバーの通知を自動的に復元できます。常駐アプリや監視アプリなど、常時通知を表示したいケースでぜひ活用してみてください。

  1. Androidスマホの再起動方法を8つ徹底解説!電源ボタンが効かないときの対処法も

    Androidスマホの不調に悩んだとき、まず試したいのが「再起動」です。定期的にデバイスを再起動することで、スマホを常に良好な状態に保つことができます。再起動には、動作速度の向上だけでなく、アプリのクラッシュや画面のフリーズ、画面が真っ暗になるといった軽微なトラブルの解消など、さまざまな効果が期待できます。 しかし、いざというときに頼りになる電源ボタンが故障していたらどうすればよいのでしょうか?この記事では、そんな困った状況を解決するための再起動方法を詳しく解説します! Androidスマホを再起動する8つの方法 #1 標準的な方法で再起動する まず最初におすすめしたいのは、スマホに搭載され

  2. Androidのステータスバーと通知バーをカスタマイズする方法|手動設定からおすすめアプリ6選まで

    Androidは、これまでに設計された中でも最もカスタマイズ性の高いOSの一つです。他のモバイルOSと比べて、自由度の高いパーソナライズ機能が提供されています。Google Playストアで「カスタマイズ」と検索すれば、ランチャーアプリ、アイコンパック、Androidテーマ、ライブ壁紙、通知バーやステータスバーのカスタマイズアプリなど、数百ものアプリがさまざまなカテゴリで表示されます。 正直なところ、ランチャーアプリを使えばスマートフォンの見た目や操作感は大きく変わります。しかし、通知センターやステータスバーといった要素までは変更できません。そこで活躍するのが、専用のカスタマイズアプリです。