我正试图检测我的通知何时被清除。 我的问题直接提到了这个答案 ,它概述了我想要做的事情。 这就是我实施这些行动的方式:
// usual Notification initialization here notification.deleteIntent = PendingIntent.getService(context, 0, new Intent(context, CleanUpIntent.class), 0); notificationManager.notify(123, notification)
这是CleanUpIntent类:
class CleanUpIntent extends IntentService { public CleanUpIntent() { super("CleanUpIntent"); } @Override protected void onHandleIntent(Intent arg0) { // clean up code } }
之后,我只是像往常一样启动通知,但是当我去测试它时(按“清除所有通知”)没有任何反应。 我插入了一行代码,当IntentService启动时,它会向LogCat打印一些内容,但是没有任何代码运行过。 这是我假设使用Notification.deleteIntent的方式吗?
您需要做的是注册BroadcastReceiver
(可能在您的AndroidManifest.xml中或者在Service
使用registerReceiver
),然后将deleteIntent
设置为将被该接收器捕获的Intent
。
用户清除通知时将调用的示例代码,希望它能为您提供帮助。
.... notificationBuilder.setDeleteIntent(getDeleteIntent()); .... protected PendingIntent getDeleteIntent() { Intent intent = new Intent(mContext, NotificationBroadcastReceiver.class); intent.setAction("notification_cancelled"); return PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); }
NotificationBroadcastReceiver.java
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if(action.equals("notification_cancelled")) { // your code } }
AndroidManifiest.xml
您应该使用getBroadcast方法而不是getService,并且应该为特定的Action注册接收器。
不需要显式接收器。 按下清除按钮时将自动调用deleteIntent。