PendingIntent works correctly for the first notification but incorrectly for the rest

AndroidNotificationsAndroid Pendingintent

Android Problem Overview


  protected void displayNotification(String response) {
	Intent intent = new Intent(context, testActivity.class);
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
	
	Notification notification = new Notification(R.drawable.icon, "Upload Started", System.currentTimeMillis());
	notification.setLatestEventInfo(context, "Upload", response, pendingIntent);
	
	nManager.notify((int)System.currentTimeMillis(), notification);
}

This function will be called multiple times. I would like for each notification to launch testActivity when clicked. Unfortunately, only the first notification launches testActivity. Clicking on the rest cause the notification window to minimize.

Extra information: Function displayNotification() is in a class called UploadManager. Context is passed into UploadManager from the activity that instantiates. Function displayNotification() is called multiple times from a function, also in UploadManager, that is running in an AsyncTask.

Edit 1: I forgot to mention that I am passing String response into Intent intent as an extra.

  protected void displayNotification(String response) {
	Intent intent = new Intent(context, testActivity.class);
	intent.putExtra("response", response);
	PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

This makes a big difference because I need the extra "response" to reflect what String response was when the notification was created. Instead, using PendingIntent.FLAG_UPDATE_CURRENT, the extra "response" reflects what String response was on the last call to displayNotification().

I know why this is from reading the documentation on FLAG_UPDATE_CURRENT. However, I am not sure how to work around it at the moment.

Android Solutions


Solution 1 - Android

Don't use Intent.FLAG_ACTIVITY_NEW_TASK for PendingIntent.getActivity, use FLAG_ONE_SHOT instead


Copied from comments:

Then set some dummy action on the Intent, otherwise extras are dropped. For example

intent.setAction(Long.toString(System.currentTimeMillis()))

Solution 2 - Android

Was struggling with RemoteViews and several different Intents for each Button on HomeScreen Widget. Worked when added these:

1. intent.setAction(Long.toString(System.currentTimeMillis()));

2. PendingIntent.FLAG_UPDATE_CURRENT

		PackageManager pm = context.getPackageManager();

		Intent intent = new Intent(context, MyOwnActivity.class);
		intent.putExtra("foo_bar_extra_key", "foo_bar_extra_value");
		intent.setAction(Long.toString(System.currentTimeMillis()));
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);
		RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		views.setOnClickPendingIntent(my_button_r_id_received_in_parameter, pendingIntent);

Solution 3 - Android

Set Action Solved this for me. Here's my understanding of the situation:


I have multiple widgets that have a PendingIntent attached to each. Whenever one got updated they all got updated. The Flags are there to describe what happens with PendingIntents that are exactly the same.

FLAG_UPDATE_CURRENT description reads much better now:

If the same PendingIntent you are making already exists, then update all the old ones to the new PendingIntent you are making.

The definition of exactly the same looks at the whole PendingIntent EXCEPT the extras. Thus even if you have different extras on each intent (for me I was adding the appWidgetId) then to android, they're the same.

Adding .setAction with some dummy unique string tells the OS. These are completely different and don't update anything. In the end here's my implementation which works as I wanted, where each Widget has its own configuration Intent attached:

Intent configureIntent = new Intent(context, ActivityPreferences.class);

configureIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

configureIntent.setAction("dummy_unique_action_identifyer" + appWidgetId);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, configureIntent,
    PendingIntent.FLAG_UPDATE_CURRENT);

UPDATE


Even better solution in case you're working with broadcasts. Unique PendingIntents are also defined by unique request codes. Here's my solution:

//Weee, magic number, just want it to be positive nextInt(int r) means between 0 and r
int dummyuniqueInt = new Random().nextInt(543254); 
PendingIntent pendingClearScreenIntent = PendingIntent.getBroadcast(context, 
    dummyuniqueInt, clearScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Solution 4 - Android

I see answers but no explanations. Also none of the answers address all possible solutions, so I'll try to make that clear.

Documentation:

> If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent.filterEquals, or different request code integers supplied to getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).

Cause of the problem:

You create 2 notifications with 2 pending intents. Each pending intent is associated with an intent:

Intent intent = new Intent(context, testActivity.class);

However, these 2 intents are equal, therefore when your 2nd notification arrives it will launch the first intent.

Solution:

You have to make each intent unique, so that no pending intents will ever be equal. How do you make the intents unique? Not by the extras you put with putExtra(). Even if the extras are different, the intents might still be equal. To make each intent unique, you must set a unique value to the intent action, or data, or type, or class, or category, or request code: (any of those will work)

  • action: intent.setAction(...)
  • data: intent.setData(...)
  • type: intent.setType(...)
  • class: intent.setClass(...)
  • category: intent.addCategory(...)
  • request code: PendingIntent.getActivity(context, YOUR_UNIQUE_CODE, intent, Intent.FLAG_ONE_SHOT);

Note: Setting a unique request code might be tricky because you need an int, while System.currentTimeMillis() returns long, which means that some digits will be removed. Therefore I would recommend to either go with the category or the action and setting a unique string.

Solution 5 - Android

I had the same problem, and was able to fix it by changing the flag to:

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Solution 6 - Android

As documentation said use unique request code:

> If you truly need multiple distinct PendingIntent objects active at > the same time (such as to use as two notifications that are both shown > at the same time), then you will need to ensure there is something > that is different about them to associate them with different > PendingIntents. This may be any of the Intent attributes considered by > Intent.filterEquals, or different request code integers supplied to > getActivity(Context, int, Intent, int), getActivities(Context, int, > Intent[], int), getBroadcast(Context, int, Intent, int), or > getService(Context, int, Intent, int).

Solution 7 - Android

Fwiw, I have had better luck with PendingIntent.FLAG_CANCEL_CURRENT than with PendingIntent.FLAG_UPDATE_CURRENT.

Solution 8 - Android

I had the same problem and i fixed it by the below steps

  1. Clear any flag for intent

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

  2. insert intent.setAction by the below code

    intent.setAction(Long.toString(System.currentTimeMillis()));

  3. for Pendingintent ,insert the below code

    PendingIntent Pintent = PendingIntent.getActivity(ctx,0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    

I hope to work with you

Solution 9 - Android

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

In PendingIntent is two int parameters, second one and the last one. Second one is "request code" and it must be unicue number (for example id of your notifiction), else if (as in your example it equals zero, it always will be overwritten).

Solution 10 - Android

// Use pending Intent and  also use unique id for display notification....
// Get a PendingIntent containing the entire back stack
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager mNotificationManager = (NotificationManager)  sqlitewraper.context.getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(id, builder.build());

Solution 11 - Android

to send data extra correctly you should send with pending intent the notification id like this: PendingIntent pendingIntent = PendingIntent.getActivity(context, (int)System.currentTimeMillis(), intent, PendingIntent.FLAG_UPDATE_CURRENT);

Solution 12 - Android

I have the same problem, and use the PendingIntent.html.FLAG_UPDATE_CURRENT to fix it.

I have checked the source code. In ActivityManagerService.java, the key method is as follows. When the flag is PendingIntent.FLAG_UPDATE_CURRENT and the updateCurrent is true. Some extras will be replaced by new and we will get an replaced PendingIntent.

    IIntentSender getIntentSenderLocked(int type, String packageName,
            int callingUid, int userId, IBinder token, String resultWho,
            int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
            Bundle bOptions) {

// ... omitted

        final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
        final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
        final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
        flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
                |PendingIntent.FLAG_UPDATE_CURRENT);

        PendingIntentRecord.Key key = new PendingIntentRecord.Key(
                type, packageName, activity, resultWho,
                requestCode, intents, resolvedTypes, flags, bOptions, userId);
        WeakReference<PendingIntentRecord> ref;
        ref = mIntentSenderRecords.get(key);
        PendingIntentRecord rec = ref != null ? ref.get() : null;
        if (rec != null) {
            if (!cancelCurrent) {
                if (updateCurrent) {
                    if (rec.key.requestIntent != null) {
                        rec.key.requestIntent.replaceExtras(intents != null ?
                                intents[intents.length - 1] : null);
                    }
                    if (intents != null) {
                        intents[intents.length-1] = rec.key.requestIntent;
                        rec.key.allIntents = intents;
                        rec.key.allResolvedTypes = resolvedTypes;
                    } else {
                        rec.key.allIntents = null;
                        rec.key.allResolvedTypes = null;
                    }
                }
                return rec;
            }
            rec.canceled = true;
            mIntentSenderRecords.remove(key);
        }

Solution 13 - Android

While create the PendingIntent object we call the PendingIntent.getActivity(mContext, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);

So here use the below code to generate the PendingIntent and send this intent to notification. So when you get another notification that will have unique requestCode to get the data of that notification only.

Random objRandom = new Random();
final PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
                mContext,
                objRandom.nextInt(100),
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

Solution 14 - Android

I had the same problem, and was able to fix it by changing the flag to:

LayoutInflater factory = LayoutInflater.from(this);            
	  final View textEntryView = factory.inflate(R.layout.appointment, null);
	  AlertDialog.Builder bulider= new AlertDialog.Builder(PatientDetail.this);
	  final AlertDialog alert=bulider.create();
	 
	
		bulider.setTitle("Enter Date/Time");
		bulider.setView(textEntryView);
		bulider.setPositiveButton("Save", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					  EditText typeText=(EditText) textEntryView.findViewById(R.id.Editdate);
					  EditText input1 =(EditText) textEntryView.findViewById(R.id.Edittime);
					  getDateAndTime(typeText.getText().toString(),input1.getText().toString());
				}
			});
		bulider.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
		
		bulider.show();
		
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser350617View Question on Stackoverflow
Solution 1 - AndroidognianView Answer on Stackoverflow
Solution 2 - AndroidViliusKView Answer on Stackoverflow
Solution 3 - AndroidObjectiveTruthView Answer on Stackoverflow
Solution 4 - AndroidsteliosfView Answer on Stackoverflow
Solution 5 - Androidmbauer14View Answer on Stackoverflow
Solution 6 - AndroidTomaszView Answer on Stackoverflow
Solution 7 - AndroidJon ShemitzView Answer on Stackoverflow
Solution 8 - AndroidWaleed A. ElgalilView Answer on Stackoverflow
Solution 9 - AndroidDmytro UbogyiView Answer on Stackoverflow
Solution 10 - AndroidMIkka MarmikView Answer on Stackoverflow
Solution 11 - AndroidAmal KronzView Answer on Stackoverflow
Solution 12 - Androidqin haoView Answer on Stackoverflow
Solution 13 - AndroidSomnathView Answer on Stackoverflow
Solution 14 - Androiduser1917789View Answer on Stackoverflow