LoginSignup
31
31

More than 5 years have passed since last update.

Androidでプッシュ通知が来たタイミングでhogehogeする

Last updated at Posted at 2015-03-26

はじめに

電話の着信と同じように、プッシュ通知取得時(端末にインストールされているすべてのアプリの通知)の挙動をアプリ側でハンドリングできないか調査したので覚え書きです。

従来のPermissionとは違い、ユーザーの明示的な設定変更が必要

"NotificationListenerService"を使用することで、すべてのアプリに来たプッシュ通知を
通知が来たタイミングで取得する事ができます。
ただし、従来のパーミッションモデルとは違いユーザー自身が、明示的に設定を変更する必要があります。

NotificationListenerService
http://developer.android.com/reference/android/service/notification/NotificationListenerService.html

具体的に...こんな感じの設定が必要。(Onにしようとするとユーザーにセキュリティのリスクを感じさせるような長い(怖い?)メッセージが表示されます)

notification_system.png

使い方

NotificationListenerServiceをextendsしたクラスを作成した後、
onNotificationPostedの中でnotificationを通知した際の処理を書くだけでOK.

public class NLService extends NotificationListenerService {

private String TAG = this.getClass().getSimpleName();

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

@Override
public void onDestroy() {
    super.onDestroy();
}

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    Intent i = new  Intent("com.example.NOTIFICATION_LISTENER_SERVICE_DEMO");
    i.putExtra("notification_msg",""
            + "ID :" + sbn.getId() + "\n"
            + "Txt :" + sbn.getNotification().tickerText + "\n"
            + "Pkg :" + sbn.getPackageName() + "\n"
            + "Tim :" + sbn.getPostTime() + "\n"
            + "\n");
    i.putExtra("getNotification",sbn.getNotification().tickerText);
    sendBroadcast(i);
}

}

おしまい

また通知の中身自体を取得する事ができるため、悪用されると、端末に来た通知を
すべてサーバー送信+収集するようなアプリケーションが容易に作られてしまうので、
セキュリティリスクに対するアプリユーザーの理解が必要です。

demo

31
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
31