18

How do I create a pending intent everytime? Currently my existing pending intent is getting replaced with a new one. I tried using FLAG_ONE_SHOT as well as CANCEL_CURRENT but it didn't work.

Elliott Beach
  • 10,459
  • 9
  • 28
  • 41
Chintan
  • 906
  • 4
  • 14
  • 30

2 Answers2

38

add a random number to the request code like that:

Intent intent = new Intent(context, YourClassname.class);
intent.putExtra("some data", "txt");  // for extra data if needed..

Random generator = new Random();

PendingIntent i=PendingIntent.getActivity(context, generator.nextInt(), intent,PendingIntent.FLAG_UPDATE_CURRENT);
Zeev G
  • 2,191
  • 21
  • 37
  • 14
    You're better off using the current timestamp as that is guaranteed to be different every second. A random number _could_ be repeated... You need to cast to a int though: `(int)(System.currentTimeMillis()/1000)` – ingh.am Oct 25 '13 at 14:28
  • 8
    In computer land the length of a second is enormous, I'd say a random number is less likely to repeat! – mxcl Dec 05 '13 at 14:00
  • 1
    @mxcl Yeah in "computer land" is much larger. But this is not computer land. ing0 is right, much better with time stamp. – Chad Bingham Dec 04 '14 at 23:11
  • Random does the job well. Thanks, – TPG Mar 19 '15 at 09:13
  • ' PendingIntent.getBroadcast(Context, rand, Intent, int) ' does this too? – guru_007 Jul 31 '17 at 04:41
  • can you please help me to fix this issue https://stackoverflow.com/questions/51267156/alarm-started-when-opening-the-app-instead-of-on-specific-time-in-android @ZeevG – Zhu Jul 10 '18 at 14:01
12

FLAG_CANCEL_CURRENT- if the described PendingIntent already exists, the current one is canceled before generating a new one.

FLAG_NO_CREATE - if the described PendingIntent does not already exist, then simply return null instead of creating it.

FLAG_ONE_SHOT - this PendingIntent can only be used once.

FLAG_UPDATE_CURRENT- if the described PendingIntent already exists, then keep it but its replace its extra data with what is in this new Intent.

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

Community
  • 1
  • 1
Tamilselvan Kalimuthu
  • 1,534
  • 1
  • 13
  • 28
  • That is for notification. I am talking about Pending Intent. Everytime it should create new Intent. – Chintan Mar 08 '13 at 16:52