Multiple calls to AlarmManager.setRepeating deliver the same Intent/PendingIntent extra values, but I supplied different ones

后端 未结 3 1968
灰色年华
灰色年华 2020-12-08 16:32

Solved while writing this question, but posting in case it helps anyone:

I\'m setting multiple alarms like this, with different values of id:

         


        
相关标签:
3条回答
  • 2020-12-08 17:23

    The solution for your problem is use Intent.FLAG_ACTIVITY_NEW_TASK

      p = PendingIntent.getBroadcast(context, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
    
    0 讨论(0)
  • 2020-12-08 17:27

    You could also use the flag PendingIntent.FLAG_UPDATE_CURRENT

    PendingIntent p = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    

    this should the work too

    0 讨论(0)
  • 2020-12-08 17:36

    The documentation for PendingIntent.getBroadcast() says:

    Returns

    Returns an existing or new PendingIntent matching the given parameters.

    The problem is that two Intents differing only in extras seem to match for this purpose. So getBroadcast() will return some random old PendingIntent (with a different EXTRA_ID) instead of a new one around the Intent I just created. The fix is to supply a data Uri and make it differ with the id, like this:

    Intent i = new Intent(MyReceiver.ACTION_ALARM, Uri.parse("timer:"+id));
    

    You can then retrieve the id number using:

    Long.parseLong(intent.getData().getSchemeSpecificPart());
    

    ...or of course supply the extra as well and use that.

    0 讨论(0)
提交回复
热议问题