How to properly clear all notification once clicked?
Asked Answered
B

2

32

I send a few notification on the notification bar, i wanted to clear all of it when one of the notification is clicked. For now I clear one by one by using Flag. I know notificationManager.cancelAll() could clear all the notification but where should i put so that i can trigger once one of the notification is clicked.

 private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name); 
    Intent notificationIntent = new Intent(context, MainActivity.class);

    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(msgid, notification);  
    //notificationManager.cancelAll(); //i wan to clear all when the notification is clicked, where should i put this line?
}
Bosnia answered 30/11, 2012 at 10:9 Comment(0)
B
90

My solution is to call it at onResume().

@Override
protected void onResume() {
super.onResume();

// Clear all notification
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
} 
Bosnia answered 3/12, 2012 at 2:52 Comment(1)
Try this NotificationManagerCompat.from(this).cancelAll();Alta
K
1

You should use a pending intent that sends a broadcast and then put in place a broadcast receiver that will cancel all your notifications. It is best to memorize all notifications IDs and delete them one by one.

Kaylyn answered 30/11, 2012 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.