How to properly clear all notification once clicke

2020-03-08 07:37发布

问题:

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?
}

回答1:

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


回答2:

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.