0

My application uses Firebase Notifications. If Firebase generates two notifications with the same id, I display both in my status bar, but I want the older notification to be removed.

My code:

  private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(119);

    notificationManager.notify(119 /* ID of notification */, notificationBuilder.build());
}
MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
Ouail Bellal
  • 1,554
  • 13
  • 27
  • You're looking to send a so-called collapsible message, which means that any new message with the same key replaces the previous message with that key. See https://firebase.google.com/docs/cloud-messaging/concept-options#collapsible_and_non-collapsible_messages – Frank van Puffelen Jul 30 '16 at 15:36
  • if you use same id for each notification. than previous notification should be replaced with new one. – Developine Jul 30 '16 at 16:24
  • how to add collapse_key parameter please ? – Ouail Bellal Jul 30 '16 at 20:13
  • If you are generating the notification yourself using the code in your question then you can simply call notify again with the same ID and that would update the existing notification or create a new one if it is the first time. Note that if you are sending notifications from the Firebase console that in some cases it would generate notifications without using your code. – Arthur Thompson Jul 31 '16 at 03:17

1 Answers1

2

If you know the Notification Id's to remove, just use

    notificationManager.cancel(id);

If you don't then use

        notificationManager.cancelAll();
Veeresh Charantimath
  • 4,641
  • 5
  • 27
  • 36