如何使用Notification.deleteIntent

问题描述 投票:0回答:4

我正在尝试检测我的通知何时被清除。我的问题直接涉及这个answer,它概述了我应该做什么。这就是我实施这些行动的方式:

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

android notifications android-intent intentservice
4个回答
52
投票

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

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

public class NotificationBroadcastReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        if(action != null && action.equals("notification_cancelled"))
        {
            // your code
        }
    }
}

AndroidManifyst.xml

 <receiver
     android:name=".NotificationBroadcastReceiver"
     android:exported="false">
     <intent-filter>
         <action android:name="notification_cancelled"/>
     </intent-filter>
 </receiver>

5
投票

您需要做的是注册一个

BroadcastReceiver
(可能在您的AndroidManifest.xml中,或者在
registerReceiver
中使用
Service
),然后将
deleteIntent
设置为将被该接收器捕获的
Intent
.


0
投票

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


-4
投票

不需要显式接收器。当按下 clear 按钮时,deleteIntent 将被自动调用。

© www.soinside.com 2019 - 2024. All rights reserved.