多次调用 AlarmManager.setRepeating 提供相同的 Intent/PendingIntent 额外值,但我提供了不同的值

编程入门 行业动态 更新时间:2024-10-11 19:19:41
本文介绍了多次调用 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));

然后您可以使用以下方法检索身份证号码:

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 额外值,但我提供了不同的值

本文发布于:2023-11-26 23:52:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:但我   setRepeating   AlarmManager   PendingIntent   Intent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!