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

user350617 picture user350617 · Jul 2, 2010 · Viewed 76.5k times · Source
  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.

Answer

ognian picture ognian · Jul 2, 2010

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