我正在创建重复警报。使用以下代码可以正常工作:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
intent.setAction("" + notificationId);
intent.putExtra(AlarmReceiver.TITLE, alarmTitle);
intent.putExtra(AlarmReceiver.SUBTITLE, alarmSubTitle);
intent.putExtra(AlarmReceiver.TICKER_TEXT, alarmTicker);
intent.putExtra(AlarmReceiver.NOTIFICATION_ID, notificationId);

 PendingIntent sender = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
 AlarmManager am = getAlarmManager();
 am.setRepeating(AlarmManager.RTC_WAKEUP, triggerTime, 60000, sender);


现在,我想取消一个现有的通知消息(出于测试目的,该消息每分钟都会弹出),我调用以下代码,并将相同的notificationId传递给它:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
intent.setAction("" + notificationId);
PendingIntent pi = PendingIntent.getService(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

     AlarmManager am = getAlarmManager();
     try {
          am.cancel(pi);

         } catch (Exception e) {
       Log.e(PLUGIN_NAME, "AlarmManager update was not canceled. " + e.toString());
}


我看到了pi != null,但是通知不断出现,并且没有被取消。两个代码段都位于同一类中。

基本上我有两个问题:
 -如何使用其唯一ID取消单个警报?
 -无论ID如何,如何取消所有警报?

更新:我发现在此处发布问题有助于理清思路。从以下位置更改取消代码:

PendingIntent sender = PendingIntent.getService( ... )

至:

PendingIntent sender = PendingIntent.getBroadcast( ... )

帮助解决问题1。但是取消所有事件的代码仍然不起作用:

Intent intent = new Intent(this.ctx, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this.ctx, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

AlarmManager am = getAlarmManager();
am.cancel(pi);

最佳答案

我是这里的菜鸟。但是我认为如果要取消警报,则必须使用完全相同的PendingIntent实例。这意味着“它们的动作,数据,类型,类和类别是相同的”,如filterEquals(Intent)所定义。因此,您需要在此处使用相同的requestCode,而不是0。也许您可以使用列表存储通知ID,然后对其进行迭代以取消所有警报。

10-06 14:18
查看更多