What's "requestCode" used for on PendingIntent?

42,524

Solution 1

  1. requestCode is used to retrieve the same pending intent instance later on (for cancelling, etc).
  2. Yes, my guess is the alarms will override each other. I would keep the request codes unique.

Solution 2

I just want to add to @Minhaj Arfin answer

1- requestCode is used to get the same pending intent later on (for cancelling etc)

2- Yes, they will get override as long as your specify the same Receiver to your Intent that you specify on your PendingIntent

example:

Intent startIntent1 = new Intent(context, AlarmReceiverFirst.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, startIntent1, 0);

Intent startIntent2 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, startIntent2, 0);

From above example, they will not override each other because the receiver is different(AlarmReceiverFirst and AlarmReceiverSecond)

Intent startIntent2 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, startIntent2, 0);

Intent startIntent3 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(context, 0, startIntent3, 0);

From above example, they will override each other, because the receiver is same(AlarmReceiverSecond)

Solution 3

Actually, the documentation clearly states what the request code is used for:

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(Intent), 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).

Since it seems that it still isn't that clear, let me try to explain:

When you want to use a PendingIntent object, you don't just instantiate one. Rather, you obtain one from the system using the PendingIntent static methods (getActivity, getBroadcast, getService etc). The system keeps a bunch of PendingIntent instances and gives you one. Which one it gives you, it depends on the input parameters you pass to these getter methods. Those input parameters are: Context, i.e. the target receiver of the intent, the Intent to use, requestCode and flags. When you pass the same Context, the same requestCode and the same Intent (meaning an intent that filterEquals with another intent), you get the same PendingIntent object. The point is that the system wants to have as few PendingIntent objects as possible, so it tends to reuse the existing ones, as much as possible.

For example, you have two calendar notifications, for two different dates. When you click on one of them, you want your app to open to the corresponding date of that notification. In that scenario, you have the same Context target, and the Intent object you are passing differ only in the EXTRA_DATA (which specifies the date that should be open). If you provide the same requestCode when obtaining the PendingIntent object, then you will end up with the same PendingIntent object. So, when creating the second notification, you will replace the old Intent object with the new EXTRA_DATA, and end up with two notifications pointing to the same date.

If you want to have two different PendingIntent objects, as you should in this scenario, you should specify a different requestCode when obtaining the PendingIntent object.

Solution 4

in my case i want to open the same activity with two different intents so if two or more FCMS are there in the tray, any one of them will only open other will not, so i changed the requests codes of pending intent then it worked.

 PendingIntent pendingIntent =
                            PendingIntent.getActivity(this, **Some unique id for all GCMS** /* Request code */, intent,
                                    PendingIntent.FLAG_ONE_SHOT);

Solution 5

one important thing about requestCode that will seriously trouble your app is when using widgets. widgets will not work after phone reboot if their requestCode are the same. that means the pendingIndent you set on the remoteViews of your widget must be set unique requestCode, usually the widgetId accompanying a number.

Share:
42,524
android developer
Author by

android developer

Really like to develop Android apps & libraries on my spare time. Github website: https://github.com/AndroidDeveloperLB/ My spare time apps: https://play.google.com/store/apps/developer?id=AndroidDeveloperLB

Updated on January 21, 2021

Comments

  • android developer
    android developer over 3 years

    Background:

    I'm using PendingIntent for alarms via AlarmManager.

    The problem:

    At first I thought that in order to cancel previous ones, I must provide the exact requestCode that I've used before to start the alarm.

    But then I've found out I was wrong, as the cancellation API says:

    Remove any alarms with a matching Intent. Any alarm, of any type, whose Intent matches this one (as defined by filterEquals(Intent)), will be canceled.

    looking at "filterEquals", the documentation says:

    Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

    so I don't get what the "requestCode" is for...

    The question:

    What is "requestCode" used for?

    What if I create multiple alarms with the same "requestCode" ? do they override each other?

  • android developer
    android developer over 10 years
    is setting the requestCode to be unique needed even in case the alarms' intents are very different (one for service A and one for service B , for example ) ? Also, how come the documentation doesn't say anything about it? Is it possible to remove all alarms of a certain type, no matter what is the requestCode?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    No, It is not necessary for different intents. And I don't know why the documentation doesn't say anything about it, but I learnt this when setting repeating alarms and also when using the same intent.
  • android developer
    android developer over 10 years
    is it only useful for cancelling alarms, or does it have additional uses?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    It is also used in onActivityResult() when you use startActivityForResult. But there are not any other significant uses that I know of. I have only used it for cancelling alarms though.
  • android developer
    android developer over 10 years
    I was talking about PendingIntent . startActivityForResult uses a normal intent.
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    You could also use startActivityForResult with PendingIntent using a proxy activity, well that's another topic.Like I said I don't think there's some other significant use other than for cancelling.
  • android developer
    android developer over 10 years
    what is the purpose of "startActivityForResult with PendingIntent using a proxy activity" ? can you give an example?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    There might not be any purpose. I'm just saying you can do it with pending intents using proxy activity, there might be some case where you'd need to.
  • android developer
    android developer over 10 years
    but what does it mean to do it? isn't PendingIntent used for allowing other apps to have some functionalities/permissions of your app? what does it mean to use it for startActivityForResult ?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    OK my bad, forget it. Simply put: -Request Code with Pending Intents are used for cancelling. -Request Code with Intents are used for onActivityResult.
  • android developer
    android developer over 10 years
    wait, so it was a mistake? ok. so the request code for pendingIntent is used only for cancelling alarms, right?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    it wasn't a mistake, i said you could do that with proxy activity, but there is no use for it. And yes, it is used for cancelling alarms.
  • android developer
    android developer over 10 years
    what do you mean "you could do that" ? do what? put a request code when calling startActivityForResult ?
  • Minhaj Arfin
    Minhaj Arfin over 10 years
    I meant you could use start activity for result with pending intent though there is no use of it. So that case is closed. Don't get confused on that statement, Coming back to your question the request code with pending intent is used for cancelling if the intents have the same action, data, type, class, and categories.
  • android developer
    android developer over 10 years
    "have the same action, data, type, class, and categories." - and the request code, as it seems. about the " startActivityForResult ", I don't get how and why will it be useful when being used with PendingIntent, but thanks anyway...
  • Someone Somewhere
    Someone Somewhere almost 9 years
    I agree; the documentation for PendingIntent and AlarmManager are total sh!t - made worse by the fact that it's not possible to list alarms programmatically.
  • Jenix
    Jenix over 7 years
    Intent startIntent4 = new Intent(context, AlarmReceiverSecond.class); PendingIntent pendingIntent4 = PendingIntent.getService(context, 0, startIntent4, 0); would be okay then? I mean, won't this override because it's calling getService() instead of getBroadcast()?
  • Jenix
    Jenix over 7 years
    Sorry to ask another question but because stackoverflow doesn't allow me to write a question without a single code line.. Doesn't the last argument of PendingIntent's methods like getBroadcast() have something to do with overriding? I used to put 0 there just like your example code above but I also saw many people were putting some specific option value instead of 0.
  • HendraWD
    HendraWD over 7 years
    @Jenix uou use AlarmReceiverSecond.class on the intent and then use PendingIntent.getService(). It will not work, since AlarmReceiverSecond.class is a BroadcastReceiver, not a Service
  • HendraWD
    HendraWD over 7 years
    About flags, it is properties that you can set, that will make the behavior of your PendingIntent according to the flags you provided. 0 means all the flags off
  • Jenix
    Jenix over 7 years
    Ah I was stupid haha What in the world was I thinking.. I was a little bit confused about PendingIntent and your answer was really helpful. And I just wanted to make it clearer but now realized my question didn't make any sense at first. Thanks!
  • Mostafa Imran
    Mostafa Imran over 7 years
    If I set different action on intent, what'd happen?
  • HendraWD
    HendraWD over 7 years
    @MostafaImran by action here, did you mean Intent.setAction();?
  • arthropod
    arthropod over 6 years
    I wonder if the documentation is purposefully bad in order to discourage people from using resources that may make the battery drain faster.
  • JSONParser
    JSONParser over 5 years
    there was no need to check the code further for my case , can you tell in which case the pending intent instance will be required. With respect to question changing request code helped me to goto correct screen, I dont know whether is this the correct way and for me error was happening only when multiple FCMs were there in tray
  • android developer
    android developer over 5 years
    So why set a different request-code, if you don't need it?
  • JSONParser
    JSONParser over 5 years
    ok i will explain in detail , i had some ACTIVITY A , it is meant to show questions i will pass the id from notifications through intent and then make a network request for that id and fetch the particular question, so what was happening that when there are more than 1 notifications in notification tray and then I click on the any one of them i get the id of question which was in the first GCM , after changing the pending intent request code to some unique value it worked. I hope i made it clear now , if any more discussion is required i am there, i also want to learn more, thank you
  • android developer
    android developer over 5 years
    Oh you meant that otherwise it wouldn't have worked at all, right? Sorry about the confusion. This question was asked a long time ago and I don't remember it well at all...
  • HendraWD
    HendraWD about 5 years
    Maybe my answer can give more clarity and certainty stackoverflow.com/a/38759473/3940133
  • android developer
    android developer about 4 years
    But as I've mentioned, to cancel alarms, you can't use just the requestCode. It doesn't mean anything for it. You will have to put extra data to differentiate between them. I don't remember but I think you can even use the same requestCode for multiple alarms.
  • Eir
    Eir about 4 years
    @androiddeveloper what you just said is incorrect. Try it.