how to use delete intent to perform some action on clear notification?

前端 未结 2 1418
无人共我
无人共我 2020-12-09 19:05

I want to reset a variable of my service when user clears my notification: that\'s all!

Looking around I see that everyone suggest to add a delete intent on my notif

2条回答
  •  清歌不尽
    2020-12-09 19:32

    Notifications are not managed by your app and all things like showing notifications and clearing them are actually happening in another process. You can't make another app directly execute a piece of code just because of security reasons.

    The only possibility in your case is to provide a PendingIntent which just wraps around a regular Intent and will be started on behalf of your app when notification is cleared. You need to use PendingIntent for sending broadcast or starting a service and then doing what you want in the broadcast receiver or in the service. What exactly to use depends on from which application component you are showing notifications.

    In case of broadcast receiver you can just create an anonymous inner class for broadcast receiver and register it dynamically before showing notification. It will look something like that:

    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);
        }
    }
    

提交回复
热议问题