对 AlarmManager.setRepeating 的多次调用提供相同的 Intent/PendingIntent 额外值,但我提供了不同的值
在编写这个问题时解决了,但发布以防万一它对任何人有帮助:
我正在设置多个这样的警报,具有不同的 id
值:
AlarmManager alarms = (AlarmManager)context.getSystemService(
Context.ALARM_SERVICE);
Intent i = new Intent(MyReceiver.ACTION_ALARM); // "com.example.ALARM"
i.putExtra(MyReceiver.EXTRA_ID, id); // "com.example.ID", 2
PendingIntent p = PendingIntent.getBroadcast(context, 0, i, 0);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, nextMillis, 300000, p); // 5 mins
...并像这样接收它们:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_ALARM)) {
// It's time to sound/show an alarm
final long id = intent.getLongExtra(EXTRA_ID, -1);
警报被发送到我的接收器在正确的时间,但通常将 EXTRA_ID
设置为错误的值:这是我在某个时刻使用过的值,只是不是我希望在该特定时间交付的值。
Solved while writing this question, but posting in case it helps anyone:
I'm setting multiple alarms like this, with different values of id
:
AlarmManager alarms = (AlarmManager)context.getSystemService(
Context.ALARM_SERVICE);
Intent i = new Intent(MyReceiver.ACTION_ALARM); // "com.example.ALARM"
i.putExtra(MyReceiver.EXTRA_ID, id); // "com.example.ID", 2
PendingIntent p = PendingIntent.getBroadcast(context, 0, i, 0);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, nextMillis, 300000, p); // 5 mins
...and receiving them like this:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_ALARM)) {
// It's time to sound/show an alarm
final long id = intent.getLongExtra(EXTRA_ID, -1);
The alarm is delivered to my receiver at the right times, but often with EXTRA_ID
set to the wrong value: it's a value that I have used at some point, just not the one that I wanted delivered at that particular time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
PendingIntent.getBroadcast()
的文档说:问题是两个仅在额外内容上不同的意图似乎与此目的相匹配。因此,getBroadcast() 将返回一些随机的旧 PendingIntent(具有不同的 EXTRA_ID),而不是围绕我刚刚创建的 Intent 的新 PendingIntent。解决方法是提供一个数据 Uri 并使其与 id 不同,如下所示:
然后您可以使用以下方法检索 id 编号:
...或者当然也提供额外的内容并使用它。
The documentation for
PendingIntent.getBroadcast()
says: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 differentEXTRA_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:You can then retrieve the id number using:
...or of course supply the extra as well and use that.
您还可以使用标志
PendingIntent.FLAG_UPDATE_CURRENT
这也应该有效
You could also use the flag
PendingIntent.FLAG_UPDATE_CURRENT
this should the work too
您的问题的解决方案是使用 Intent.FLAG_ACTIVITY_NEW_TASK
The solution for your problem is use Intent.FLAG_ACTIVITY_NEW_TASK