9

When creating a new notification with a new PendingIntent, the extras in its intent override any previous notification's PendingIntent Intent extras.

For example, lets say I create Notification1 with PendingIntent1, which has Intent1 and its extras.

When I create Notification2 with PendingIntent2, which has Intent2 with its own different extras, Intent1 will now have the same extras as Intent2. Why is this happening? How do I work around this?

b.lyte
  • 6,518
  • 4
  • 40
  • 51
  • 1
    Android is using the same `PendingIntent` for both notifications, which is why `Intent1` and `Intent2` have the same extras. When you create the `PendingIntent` you need to make sure that they are unique so that you don't end up reusing the same `PendingIntent`. There are several ways to make them unique (different ACTION, different DATA, different REQUEST_CODE), unfortunately just having different EXTRAS doesn't make them unique. – David Wasser Jul 18 '14 at 11:39
  • By default ( if no flags are passed prior to send your notifications ) intent2 extras are beaten by intent1's. – stdout Jul 27 '16 at 17:20

2 Answers2

36

There are two ways to solve this:

One is to set a different action on the Intent. So in your example, you could set Intent1.setAction("Intent1") and Intent2.setAction("Intent2"). Since the action is different, Android will not override the extras on the intent.

However, there may be a case where you actually need to set a specific action on this intent (i.e. your action corresponds to a specific broadcast receiver). In this case, the best thing to do is set the request code to something different in each PendingIntent:

PendingIntent pendingIntent1 = PendingIntent.getActivity(context,
    (int) System.currentTimeMillis() /* requestCode */, intent1, 
    PendingIntent.FLAG_UPDATE_CURRENT);

PendingIntent pendingIntent2 = PendingIntent.getActivity(context,
    (int) System.currentTimeMillis() /* requestCode */, intent2, 
    PendingIntent.FLAG_UPDATE_CURRENT);

By setting a new request code on the PendingIntent, Android will not override the extras on each of their corresponding intents.

b.lyte
  • 6,518
  • 4
  • 40
  • 51
5

In my case it worked with by using unique notification id each time like below:

mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());

Generate the unique id each by using (int) System.currentTimeMillis() and give this to NotificationManager object.

AdrieanKhisbe
  • 3,899
  • 8
  • 37
  • 45
Rahul_Pawar
  • 572
  • 1
  • 8
  • 16
  • 1
    This only prevent notifications from overriding each other (So that the app can show multiple notifications at the same time), but not the pending intent's extra. – Sira Lam Jun 20 '18 at 06:47
  • 1
    But one could also apply the same idea to the pending intent request code – Punpuf Feb 14 '19 at 02:54