How to cancel an alarm from AlarmManager

I faced the same problem. Delete alarm from AlarmManager using cancel () function - Android

"I'm trying to create and delete an alarm in two different methods that are called at different times in the application. Logic.

However, when I call the AlarmManager cancel () method, the alarm is not deleted. "

To install:

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

To delete:

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

But this does not delete the recorded alarm. Thanks in advance.

+7
android
source share
2 answers

The PendingIntent needs to be created exactly as it was when starting AlarmManager, and it seems that the main problem is that you are 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); 

To use the PendingIntent.FLAG_UPDATE_CURRENT flag, see below:

Installation:

 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); 

Cancel

 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); 
+17
source share

Initially, it didn’t work for me either. After looking at many messages, I realized that the pending intention to be canceled should be the same as the original pending intention that was used to plan the alert. The expected intention to be canceled should be set to the same action and the same data fields, if any, were used to set the alarm. After setting the same ACTION values ​​and data, although I do not use them, I just canceled Alarm.

0
source share

All Articles