How to cancel alarm from AlarmManager

The PendingIntent needs to be created exactly as it was when you start the AlarmManager, and it looks like the main issue is that you’re using a different requestCode (zero instead of one).

For a quick fix, this should work:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                 getApplicationContext(), 1, myIntent, 0);

alarmManager.cancel(pendingIntent);

In order to use PendingIntent.FLAG_UPDATE_CURRENT flag, see below:

Setting:

Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                getApplicationContext(), 1, myIntent, 
                                PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC, now.getTimeInMillis(), pendingIntent);

Cancelling:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), SessionReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                getApplicationContext(), 1, myIntent, 
                                PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.cancel(pendingIntent);

Leave a Comment