【问题标题】:Delete specific Alarm from AlarmManager从 AlarmManager 中删除特定警报
【发布时间】:2013-07-25 13:01:53
【问题描述】:

我想删除我在广播接收器中设置的警报。 这是它应该如何执行的:

我收到一条 GCM 消息,其中包含一个 user_state 字段。

如果 user_state 为 0 则不触发通知 如果 user_state 为 1,则触发通知 如果 user_state 为 2,则设置警报并在 20 分钟后触发通知。

这一切都很好。

现在我想删除一个特定的警报,具体取决于从 GCM 意图接收到的数据。 不幸的是 AlarmManager.cancel() 不比较额外的字段。 我也尝试使用 intent.setType("data to compare") 但如果我设置此字段,则不会收到广播...

我现在尝试使用应该在 Action 字段中进行比较的数据注册一个新的 BroadcastReceiver。 据我了解,这应该可以正常工作,但是无法从 BroadcastReceiver 中注册 BroadcastReceiver。

此外,无法从 AlarmManager 中获取 Pendingintents 列表。 所以我现在能做的就是删除所有警报 - 这不是一个选项,

我唯一的另一个想法是使用我自己的服务而不是警报管理器......我想避免那个。当有内置选项时,我不想使用额外的资源。

这是我设置的报警方法:

private void setTimed(Intent intent, Notify notify) {
    Bundle bundle = intent.getExtras();
    bundle.remove("userstate");
    bundle.putString("userstate", "3");

    Intent ringintent = new Intent("de.pluetzner.waveobserver.TRECEIVE");
    ringintent.setType(notify.getHost()+"&&&"+notify.getService());
    ringintent.putExtras(bundle);
    AlarmManager am = (AlarmManager) this.context.getSystemService(this.context.ALARM_SERVICE);
    PendingIntent pi = PendingIntent.getBroadcast(this.context, 0, ringintent, 0);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (this.waittime * 60 * 1000), pi);
    Log.d("timer", "time set");
}

ringintent.setType() 应该是警报的标识符,但这不起作用。 没有这个,就会收到警报

这里是删除警报的方法。

private void deleteAlarm(Intent intent, Notify notify) {
    Intent ringintent = new Intent("de.pluetzner.waveobserver.TRECEIVE");
    ringintent.setType(notify.getHost() + "&&&" + notify.getService());
    PendingIntent pi = PendingIntent.getBroadcast(this.context, 0, ringintent, 0);
    AlarmManager am = (AlarmManager) this.context.getSystemService(this.context.ALARM_SERVICE);
    am.cancel(pi);
    Log.d("timer", "time removed");
}

这里也一样——设置了 setType 就不行了。没有它,它会删除每个警报。

我也知道这会以某种方式滥用 setType - 但我没有想法。你有吗?

【问题讨论】:

  • 确定吗?据我了解,我还需要重建完全相同的 PendingIntent - 这给我留下了同样的问题。

标签: android broadcastreceiver alarmmanager intentfilter


【解决方案1】:

getBroadcast 方法的RequestCode 参数唯一标识每个PendingIntent。

您可以为每个 PendingIntent 分配一个唯一的整数代码。

报警1:

      PendingIntent pi = PendingIntent.getBroadcast(this.context, 1, ringintent, 0); 

报警2:

      PendingIntent pi = PendingIntent.getBroadcast(this.context, 2, ringintent, 0); 

现在如果你想单独杀死Alarm2,重新创建具有相同标识符的PendingIntent,然后调用AlarmManager的cancel方法

      PendingIntent sender = PendingIntent.getBroadcast(this, 2, intent, 0);
      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
      alarmManager.cancel(sender);

【讨论】:

  • 老实说,我不确定这是否能解决问题。自从我从事这个应用程序以来已经有很长时间了。无论如何我都会接受你的答案:D
猜你喜欢
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
相关资源
最近更新 更多