如何使用删除意图在清除通知时执行某些操作?

15

当用户清除我的通知时,我希望重置我的服务变量:仅此而已!

我查看了一下,发现每个人都建议在我的通知中添加一个删除意图,但是意图是用于启动活动、服务或其他内容的,而我只需要像这样的东西:

void onClearPressed(){
   aVariable = 0;
}
如何获得这个结果?
2个回答

45

通知并非由您的应用程序管理,所有显示通知和清除通知等操作实际上是在另一个进程中执行的。出于安全原因,您不能直接让另一个应用程序执行代码。

在您的情况下,唯一的可能性是提供一个PendingIntent,它仅包装了常规意图,并将在通知被清除时代表您的应用程序启动。 您需要使用PendingIntent来发送广播或启动服务,然后在广播接收器或服务中执行所需操作。具体要使用什么取决于您显示通知的应用程序组件。

对于广播接收器,您可以创建一个匿名内部类来注册动态广播接收器,然后显示通知。代码大致如下:

public class NotificationHelper {
    private static final String NOTIFICATION_DELETED_ACTION = "NOTIFICATION_DELETED";

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            aVariable = 0; // Do what you want here
            unregisterReceiver(this);
        }
    };

    public void showNotification(Context ctx, String text) {
        Intent intent = new Intent(NOTIFICATION_DELETED_ACTION);
        PendingIntent pendintIntent = PendingIntent.getBroadcast(ctx, 0, intent, 0);
        registerReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));
        Notification n = new Notification.Builder(mContext).
          setContentText(text).
          setDeleteIntent(pendintIntent).
          build();
        NotificationManager.notify(0, n);
    }
}

1
我正在尝试使用IntentService。出现了一个异常:意图接收器泄漏了。"您是否缺少调用unregisterReceiver的调用?" 有人能否对此进行解释? - Yasir
3
注册和注销接收器应该在未引用的上下文中调用,因此在您的IntentService中使用getApplicationContext()应该可以解决您的问题。 - smora
1
我建议注册静态接收器(例如在AndroidManifest中注册的接收器),因为应用程序可能在用户关闭通知时被杀死。静态接收器确保即使应用程序已经死亡,代码也将被执行。 - pepyakin
只有公共类或静态嵌套类才能静态注册广播接收器。因此,您无法访问要更改的变量的上下文。 - Rule

1

Andrei是正确的。
如果您想要多个消息返回,例如:

  • 您想知道消息是否被点击
  • 您附加了一个带有图标的操作,您想要捕获
  • 并且您想知道消息是否被取消

您必须注册每个响应过滤器:

public void showNotification(Context ctx, String text) ()
{
    /… create intents and pending intents same format as Andrie did../
    /… you could also set up the style of your message box etc. …/

    //need to register each response filter
    registerReceiver(receiver, new IntentFilter(CLICK_ACTION));
    registerReceiver(receiver, new IntentFilter(USER_RESPONSE_ACTION));
    registerReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));

    Notification n = new Notification.Builder(mContext)
      .setContentText(text)
      .setContentIntent(pendingIntent)                          //Click action
      .setDeleteIntent(pendingCancelIntent)                     //Cancel/Deleted action
      .addAction(R.drawable.icon, "Title", pendingActionIntent) //Response action
      .build();

    NotificationManager.notify(0, n);

}

然后,您可以使用if、else语句(如Andrei所做的那样)或switch语句来捕获不同的响应。
注意:我主要提供此响应是因为我在其他地方找不到这个答案,我不得不自己弄清楚它。(也许我会更好地记住它 :-) 玩得开心!

哦,你还应该考虑查找NotificationCompat.Builder。 - Chuck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接