Android AlarmManager: is there a way to cancell ALL the alarms set?

Lis*_*nne 14 android alarmmanager

I am building an app that set 2 alarms for each day of the week (at a certain hour and minute), the alarms repeat week after week forever.

Now the point is: if the user changes the alarms, I will need cancel the previously set alarms.

Is there a way to simply cancel all the alarms set by my application ?

imt*_*iga 17

如果要取消先前的警报,那么在PendingIntent中,您的标志应为PendingIntent.FLAG_CANCEL_CURRENT.如果已经创建了PendingIntent,它将阻止生成新的PendingIntent.并确保在设置闹钟之前取消相同的PendingIntent并在此之后设置闹钟.你应该这样试试:

AlarmManager 2AlarmsInWeekAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService/getActivity(context, int, intent, PendingIntent.FLAG_CANCEL_CURRENT);

2AlarmsInWeekAlarmManager.cancel(pendingIntent);
Run Code Online (Sandbox Code Playgroud)

然后你可以使用set或setRepeating方法.在你的情况下它应该是

2AlarmsInWeekAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, "timeInMillis", "repetitionTimeInMillis", pendingintent);
Run Code Online (Sandbox Code Playgroud)

这可以保证在设置警报之前将使用相同的PendingIntent取消所有先前的警报.

希望你有这个!

  • 要取消警报,你需要重新创建确切的`PendingIntent`,我想没有办法直接从代码中检索它.你仍然可以在shell中看到待处理的警报!如果您熟悉adb shell,可以使用以下命令来实现:`adb shell dumpsys alarm> log.txt`其中`log.txt`将包含所有包含程序包名称的待处理警报,因此您可以查看自己的警报.我不知道如何从代码中获取它. (3认同)

小智 10

我想你可以关注一下:AlarmManager.Cancel

在那个问题/答案:Android:获取所有使用AlarmManager设置的PendingIntents

如前所述,您无法要求AlarmManager告诉您其中的PendingIntent.但我认为你可以使一些PendingIntent类似于你要取消的那个;).


Soh*_*ari 5

我在取消闹钟时遇到了同样的问题,并解决了它。你应该做的就是简单地做——

  1. 创建警报时,保存PendingIntent对象的请求代码(到共享首选项)。
  2. 稍后,当您想要取消警报时,请 使用相同的请求代码(显然来自共享首选项)创建相同的 PendingIntent。
  3. 调用AlarmManager的cancel()并传入PendingIntent对象,闹钟就会被取消。

    private void cancelAlarm(int requestCode) {
    
    AlarmManager alarmManager2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    
    PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(),requestCode,new Intent(this, MyBroadCastReceiver.class),0);
    alarmManager2.cancel(pendingIntent2);
    
    Toast.makeText(getApplicationContext(), "Alarm Cancelled - "+ requestCode, Toast.LENGTH_LONG).show();
    
    Run Code Online (Sandbox Code Playgroud)

    }