Is it possible to cancel all notifications that have a certain tag?
Asked Answered
A

4

12

I'm making an android app and I would like to cancel all notifications that have a certain tag.

Right now it only seems possible to cancel notifications by their id (int id) or by both their ids and tags.

mNotificationManager.cancel(int id);

or

mNotificationManager.cancel(String tag, int id);

I want to be able to cancel all notifications of String tag regardless of int id.

Is this possible?

Adaiha answered 12/3, 2016 at 17:56 Comment(0)
W
7

No, it isn't. The way Notification is set up, id is the primary key. You can add a subkey with tag, and cancel an individual (tag, id) pair that way, but you can't cancel based on tag alone. Really I'm not sure why they added a tag parameter, as it seems rather redundnt, except that possibly a string parameter makes for easier debugging.

Wimble answered 12/3, 2016 at 18:0 Comment(3)
Tags are very useful when you are developing an app with multiple components using notifications. If you set a tag for each component, you don't have to worry about the uniqueness of the ids in the context of all of the components. They just have to be unique locally.Soke
@Soke about which components you are talking? and can you give me code example of tag use?Spriggs
@Gabe how tag could be useful for debugging purpose?Spriggs
H
4

Yes , it is possible

  1. Get all active notification build by your app using mNotificationManager.getActiveNotifications()
  2. Filter Notification based on TAG.
  3. Cancel those notifications.

Try below code

void cancelGivenTagNotification(String tag){
    StatusBarNotification notiList[] = notificationManager.getActiveNotifications();
    for(int i=0;i<notiList.length;i++){
        if(notiList[i].getTag().equals(tag)){
            int notiId = notiList[i].getId();
            notificationManager.cancel(tag,notiId);
        }

    }
}
Hyaluronidase answered 3/1, 2022 at 10:20 Comment(0)
C
2

On Android using API >= 23 you can do something like this to remove a group of notifications:

for (StatusBarNotification statusBarNotification : mNotificationManager.getActiveNotifications()) {
    if (KEY_MESSAGE_GROUP.equals(statusBarNotification.getGroupKey())) {
        mNotificationManager.cancel(statusBarNotification.getId());
    }
}
Clement answered 12/12, 2017 at 11:53 Comment(0)
P
2

Seems possible if you use notification groups. Cancelling the group summary notification seems to cancel the entire group.

Philine answered 19/1, 2018 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.