多次调用 AlarmManager.setRepeating 提供相同的 Intent/PendingIntent 额外值,但我提供了不同的值 [英] Multiple calls to AlarmManager.setRepeating deliver the same Intent/PendingIntent extra values, but I supplied different ones
问题描述
在写这个问题时解决了,但发布以防它对任何人有帮助:
Solved while writing this question, but posting in case it helps anyone:
我正在设置多个这样的闹钟,使用不同的 id
值:
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);
警报在正确的时间发送给我的接收器,但通常将 EXTRA_ID
设置为错误的值:这是我在某个时候使用过的值,只是不是我想要的值在那个特定时间交付.
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.
推荐答案
PendingIntent.getBroadcast()
的文档说:
退货
返回匹配给定参数的现有的或新的 PendingIntent.
Returns an existing or new PendingIntent matching the given parameters.
问题是两个 Intent 仅在附加项上不同,似乎与此目的相匹配.所以 getBroadcast()
将返回一些随机的旧 PendingIntent(具有不同的 EXTRA_ID
)而不是围绕我刚刚创建的 Intent 的新 PendingIntent.解决方法是提供一个数据 Uri 并使其与 id 不同,如下所示:
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.
这篇关于多次调用 AlarmManager.setRepeating 提供相同的 Intent/PendingIntent 额外值,但我提供了不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!