How to dismiss notification after action has been clicked

Viewed 128742

Since API level 16 (Jelly Bean), there is the possibility to add actions to a notification with

builder.addAction(iconId, title, intent);

But when I add an action to a notification and the action is pressed, the notification is not going to be dismissed. When the notification itself is being clicked, it can be dismissed with

notification.flags = Notification.FLAG_AUTO_CANCEL;

or

builder.setAutoCancel(true);

But obviously, this has nothing to with the actions associated to the notification.

Any hints? Or is this not part of the API yet? I did not find anything.

10 Answers

You will need to run the following code after your intent is fired to remove the notification.

NotificationManagerCompat.from(this).cancel(null, notificationId);

NB: notificationId is the same id passed to run your notification

Just for conclusion:

NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

Intent intent = new Intent(context, MyNotificationReceiver.class);
intent.putExtra("Notification_ID", 2022);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
            context,
            0,
            intent,
            ...);

Notification notification = new NotificationCompat.Builder(...)
...    
.addAction(0, "Button", pendingIntent)
.build();

notificationManager.notify(2022, notification);

and for dismiss the notification, you have two options:

approach 1: (in MyNotificationReceiver)

NotificationManager manager = (NotificationManager)
            context.getSystemService(NOTIFICATION_SERVICE);
    manager.cancel(intent.getIntExtra("Notification_ID", -1));

approach 2: (in MyNotificationReceiver)

NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.cancel(intent.getIntExtra("Notification_ID", -1));

and finally in manifest:

<receiver android:name=".MyNotificationReceiver" />

builder.setAutoCancel(true);

Tested on Android 9 also.

Related