到AlarmManager.setRepeating多个电话提供相同的意向/的PendingIntent额外的价值,但我提供不同的人

StackOverflow https://stackoverflow.com/questions/2844274

解决在写这个问题,但如果发布它可以帮助任何人:

我设置多个报警这样,与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设置为错误的值:它是我在某些时候使用,只是没有,我想在那个特定的时间中提供的一个值<。 / p>

有帮助吗?

解决方案

PendingIntent.getBroadcast()文档说:

  

<强>返回

     

,则返回一个现有的或新的PendingIntent匹配给定的参数。

的问题是,两个目的只在额外不同似乎与用于此目的。所以getBroadcast()将返回,而不是仅仅创造了周围的意图我一个新的一些随机老的PendingIntent(具有不同EXTRA_ID)。解决方法是提供一个数据URI,并使其与ID不同,这样的:

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

可以然后使用检索的ID号:

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

...当然提供额外以及并使用它。

其他提示

您也可以使用该标志PendingIntent.FLAG_UPDATE_CURRENT

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

这应该工作太

为您的问题的解决方案是使用Intent.FLAG_ACTIVITY_NEW_TASK

  p = PendingIntent.getBroadcast(context, 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top