18

我正在尝试检测我的通知何时被清除。我的问题直接指的是这个答案,它概述了我应该做什么。这就是我执行这些操作的方式:

// 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 的方式吗?

4

4 回答 4

50

每当用户清除通知时都会调用的示例代码,希望对您有所帮助。

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

AndroidManifyt.xml

 <receiver android:name=".NotificationBroadcastReceiver">
                <intent-filter>
                    <action android:name="notification_cancelled"/>
                </intent-filter>
            </receiver>
于 2013-02-06T07:21:51.290 回答
4

您需要做的是注册 a BroadcastReceiver(可能在您的 AndroidManifest.xml 中或registerReceiver在 a 中使用Service),然后设置deleteIntentIntent将被该接收器捕获的 a 。

于 2011-09-19T02:19:23.200 回答
0

您应该使用 getBroadcast 方法而不是 getService 并且应该为特定操作注册接收器。

于 2012-07-19T15:16:51.123 回答
-4

不需要显式接收器。按下清除按钮时将自动调用 deleteIntent 。

于 2013-05-24T09:49:04.430 回答