I want to cancel all the alarms that are set. I have searched a lot and tried a lot of things but nothing worked. When I set an alarm for say after 2 minutes and then I cancel it, it will still fire after 2 minutes.
The method used to create the alarms:
Intent intent = new Intent(c, AlarmReceiver.class);
intent.putExtra("task", task);
intent.putExtra("id", id);
PendingIntent pendingIntent = PendingIntent.getActivity(c, code, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
This is to cancel alarms:
Intent intent = new Intent(c, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(c, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
Any help will be appreciated.
When you schedule your alarms, your second parameter to getActivity()
is code
and when you try to cancel your alarms, your second parameter to getActivity()
is 0
. This will only successfully cancel an alarm whose code
was 0
.
If you want to consistently cancel the alarms, you need to create equivalent PendingIntents
, which means the same Intent object (with the same action, component, data, flags and other attributes) and the same code. It's worth mentioning that the Context
you used to create the Intent
does not need to be the same for cancellation to see it as the same.