Hirak Chhatbar Hirak Chhatbar - 8 days ago 6
Android Question

cancel all the alarms set using alarmmanager

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 alarm for say after 2 minutes and then I cancel it, it will still fire after 2 minutes.....
Any help will be appreciated.

Method for creating 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);

Answer

When you schedule your alarms, your second parameter to getActivity() is code.

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, and that means, among other things, that the second parameter to getActivity() needs to be the same.