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

Pha*_*ate 13 android

当用户清除我的通知时,我想重置我的服务变量:这就是全部!

环顾四周,我看到每个人都建议在我的通知上添加删除意图,但意图用于启动活动,服务o无论什么时候我只需要这样的事情:

void onClearPressed(){
   aVariable = 0;
}
Run Code Online (Sandbox Code Playgroud)

如何获得这个结果?

And*_*ich 42

通知不是由您的应用管理的,所有显示通知和清除通知的内容实际上都发生在另一个进程中.由于安全原因,您不能让另一个应用程序直接执行一段代码.

在您的情况下,唯一的可能性是提供一个PendingIntent只包含常规Intent的代码,并在通知被清除时代表您的应用启动.您需要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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注册和取消注册应该从非引用上下文调用Receiver,因此在intentService中使用getApplicationContext()可以解决您的问题. (3认同)