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);
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.
You are setting the alarm with request code (second parameter for getActivity
) equals to code
, while when you are cancelling the alarm, the second parameter is 0
. If the value of code
is not 0
the alarm wouldn't be cancelled.
In order to fire and cancel multiple alarms, you need to use unique value for requestCode
(second parameter) in PendingIntent.getActivity
see this code that will set 3 Alarms using three unique request Codes,
for (int requestCode = 1; requestCode <= 3; requestCode++) {
PendingIntent pendingIntent = PendingIntent.getActivity(c, requestCode, intent,PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
You can cancel the Alarm using the same requestCode
(and other parameters) that were used to set it.
The other parameters which are needed to matched are,
Intent
must be the same (or both null). Otherwise they do not match.Intent
must be the same (or both null). Otherwise they do not match.Intent
must be the same (or both null). Otherwise they do not match.Intent
must be the same (or both null). Otherwise they do not match. "package" and "component" fields are set for "explicit" Intent
s.Intent
must be the same. Otherwise they do not match.Please see this answer for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With