/ / Comment effacer correctement toutes les notifications une fois cliqué? - android, android-notifications, notificationmanager

Comment effacer correctement toutes les notifications une fois cliqué? - android, android-notifications, notificationmanager

J'envoie quelques notifications sur la barre de notification, je voulais tout effacer lorsque l'on clique sur l'une des notifications. Pour l'instant, j'efface un par un en utilisant Flag. je connais notificationManager.cancelAll() pourrait effacer toute la notification, mais où devrais-je mettre afin que je puisse déclencher une fois que l'un de la notification est cliqué.

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

Réponses:

63 pour la réponse № 1

Ma solution est de l'appeler au onResume().

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

// Clear all notification
NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nMgr.cancelAll();
}

1 pour la réponse № 2

Vous devez utiliser une intention en attente qui envoie unediffusez puis mettez en place un récepteur de diffusion qui annulera toutes vos notifications. Il est préférable de mémoriser tous les ID de notification et de les supprimer un par un.