Android AlarmManager: is there a way to cancell ALL the alarms set?
I had same problem for cancelling alarms, and solved it. What you should do is simply do -
- When you create alarms, save request code of PendingIntent object (to shared preference).
- At later, when you want to cancel the alarm, create the same PendingIntent with the same request code (obviously from shared preference).
Call cancel() of AlarmManager and pass the PendingIntent object in it, and alarm will be cancelled.
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();
}
I think you could get an eye on : AlarmManager.Cancel
And on that Question/Answer: Android: Get all PendingIntents set with AlarmManager
As stated in there you can't ask to the AlarmManager to tell you what PendingIntent are in it. But I think you can make some PendingIntent similar to the one you want to cancel ;).
if you are canceling previous alarms then in PendingIntent
your flag should be PendingIntent.FLAG_CANCEL_CURRENT
. It will prevent generating a new PendingIntent
if it is already created. And make sure that before setting in alarm just cancel that same PendingIntent
and after that set your alarm. You should try like this:
AlarmManager 2AlarmsInWeekAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService/getActivity(context, int, intent, PendingIntent.FLAG_CANCEL_CURRENT);
2AlarmsInWeekAlarmManager.cancel(pendingIntent);
and then you may use set or setRepeating
method.
In your case it should be
2AlarmsInWeekAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, "timeInMillis", "repetitionTimeInMillis", pendingintent);
This guarantees that before setting an alarm will cancel all previously alarm with the same PendingIntent
.
Hope you got this!