多次调用AlarmManager.setRepeating会提供相同的Intent / PendingIntent额外值,但我提供了不同的值 [英] Multiple calls to AlarmManager.setRepeating deliver the same Intent/PendingIntent extra values, but I supplied different ones

查看:136
本文介绍了多次调用AlarmManager.setRepeating会提供相同的Intent / PendingIntent额外值,但我提供了不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写此问题时已解决,但要发布以防万一,它可以帮助任何人:

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

然后您可以使用以下方式检索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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆