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

Androidでステータスバー通知を傍受する方法|NotificationListenerServiceの実装手順を解説

はじめに

本記事では、NotificationListenerService を利用して、Android端末のステータスバー通知を傍受(取得)する方法を解説します。この仕組みを使えば、他のアプリが投稿した通知の内容やパッケージ名をリアルタイムで受け取ることが可能になります。通知の監視ツールやログ記録アプリなどを開発したい場合に役立つテクニックです。

ステップ1:新規プロジェクトの作成

まずは Android Studio で新しいプロジェクトを作成します。「File」⇒「New Project」を選択し、必要な項目を入力してプロジェクトを作成してください。

ステップ2:リスナーインターフェースの作成

src/MyListener.java に以下のコードを追加します。サービス側で検知した通知イベントをアクティビティへ伝えるためのコールバックインターフェースです。

public interface MyListener {
    void setValue(String packageName);
}

ステップ3:通知リスナーサービスの実装

次に、src/NotificationService.java に以下のコードを追加します。NotificationListenerService を継承したクラスを作成し、通知の「投稿」と「削除」の各イベントを onNotificationPosted() / onNotificationRemoved() で受け取ります。

package app.tutorialspoint.com.notifyme;

import android.content.Context;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;

public class NotificationService extends NotificationListenerService {

    private String TAG = this.getClass().getSimpleName();
    Context context;
    static MyListener myListener;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        Log.i(TAG, "********** onNotificationPosted");
        Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
        myListener.setValue("Post: " + sbn.getPackageName());
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        Log.i(TAG, "********** onNotificationRemoved");
        Log.i(TAG, "ID :" + sbn.getId() + "\t" + sbn.getNotification().tickerText + "\t" + sbn.getPackageName());
        myListener.setValue("Remove: " + sbn.getPackageName());
    }

    public void setListener(MyListener myListener) {
        NotificationService.myListener = myListener;
    }
}

ステップ4:メニューリソースの作成

res/menu/menu_main.xml に以下のコードを追加します。ここで定義する「Settings」メニューから、後述する通知アクセス権限の設定画面を開けるようにします。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    tools:context=".MainActivity">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="Settings"
        app:showAsAction="never" />
</menu>

ステップ5:レイアウトの作成

res/layout/activity_main.xml に以下のコードを追加します。画面上部に通知を作成するボタンを配置し、その下に傍受した通知のログを表示する TextView を ScrollView 内に設置しています。

<?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">

    <Button
        android:id="@+id/btnCreateNotification"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:text="Create Notification" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnCreateNotification"
        android:layout_alignStart="@+id/btnCreateNotification"
        android:layout_alignEnd="@+id/btnCreateNotification"
        android:layout_alignParentBottom="true">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="NotificationListenerService Example"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </ScrollView>

</RelativeLayout>

ステップ6:メインアクティビティの実装

src/MainActivity.java に以下のコードを追加します。ボタンをタップするとテスト用の通知を生成し、傍受した通知のパッケージ名を TextView に追記表示します。また、メニューの「Settings」を選択すると、システムの通知リスナー設定画面(ACTION_NOTIFICATION_LISTENER_SETTINGS)が開きます。

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements MyListener {

    private TextView txtView;
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new NotificationService().setListener(this);
        txtView = findViewById(R.id.textView);
        Button btnCreateNotification = findViewById(R.id.btnCreateNotification);
        btnCreateNotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NotificationManager mNotificationManager = (NotificationManager)
                        getSystemService(NOTIFICATION_SERVICE);
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(MainActivity.this, default_notification_channel_id);
                mBuilder.setContentTitle("My Notification");
                mBuilder.setContentText("Notification Listener Service Example");
                mBuilder.setTicker("Notification Listener Service Example");
                mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
                mBuilder.setAutoCancel(true);
                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);
                    mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
                    assert mNotificationManager != null;
                    mNotificationManager.createNotificationChannel(notificationChannel);
                }
                assert mNotificationManager != null;
                mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void setValue(String packageName) {
        txtView.append("\n" + packageName);
    }
}

ステップ7:マニフェストの設定

最後に、AndroidManifest.xml に以下のコードを追加します。ポイントは、service 要素に android.permission.BIND_NOTIFICATION_LISTENER_SERVICE パーミッションを指定し、intent-filter で NotificationListenerService のアクションを宣言することです。これにより、システムが本サービスを通知リスナーとして認識できるようになります。

<?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" />

    <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>

        <service
            android:name=".NotificationService"
            android:label="@string/app_name"
            android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
            <intent-filter>
                <action android:name="android.service.notification.NotificationListenerService" />
            </intent-filter>
        </service>
    </application>

</manifest>

アプリの実行と動作確認

それでは、アプリを実行してみましょう。実際の Android 端末を PC に接続しているものとして説明を進めます。Android Studio から実行するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続済みのモバイルデバイスを選択すると、端末にアプリの初期画面が表示されます。

Androidでステータスバー通知を傍受する方法|NotificationListenerServiceの実装手順を解説

重要: 初回起動時は、メニューの「Settings」から通知リスナー設定画面を開き、本アプリの「通知へのアクセス」を許可しておく必要があります。許可しない限り、NotificationListenerService は通知イベントを受け取れませんのでご注意ください。権限を付与した後、「Create Notification」ボタンをタップして通知を生成すると、傍受した通知のパッケージ名が画面下部の TextView に「Post: パッケージ名」という形式で追記されていきます。通知を削除した場合も同様に「Remove: パッケージ名」として記録されます。

  1. 【Access】ステータスバーの表示・非表示を切り替える方法をわかりやすく解説

    ステータスバーとは、ウィンドウの最下部に位置する横長の領域で、さまざまな状態情報を表示するためのものです。Accessのステータスバーでは、バー上に配置されたコントロールを使用して、アクティブなウィンドウのビューを簡単に切り替えることができます。 Accessでステータスバーを非表示にする手順 Accessのステータスバーをオフにするには、以下の手順に従ってください。 メニューバーの「ファイル」タブをクリックします。 バックステージビューが開いたら、「オプション」をクリックします。 「Accessのオプション」ダイアログボックスが表示されます。 左側のペインから「現在のデータベース」をクリ

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

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