Unable to check if alarm has been set by AlarmManager

Kevin Richards picture Kevin Richards · Jun 5, 2015 · Viewed 7.7k times · Source

I am checking if the alarm has already been set by the AlarmManager using this answer.

Following is my code snippet.

boolean alarmUp = (PendingIntent.getBroadcast(MainActivity.this, 0,
    new Intent(MainActivity.this, AlarmReceiver.class), PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
    // alarm is set; do some stuff
}

Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10 * 1000, pendingIntent);

However, alarmUp is always being set as true. That is, whether I set the alarm or not, whenever I restart my app, it tell me that alarmUp is true (I am checking it by making a Toast).

Please help where I am going wrong.

Answer

David Wasser picture David Wasser · Jun 15, 2015

In order for this check to work, you need to be absolutely sure that the PendingIntent only exists when the alarm is set. There are 2 things you can do to ensure that is so:

1) When testing your code, make sure that you uninstall your application and then reinstall your application before testing it. Uninstalling your app will remove any PendingIntents that your app might have created that are still pending.

2) When you cancel the alarm, make sure that you also cancel the PendingIntent. You can do this with

Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
final PendingIntent pendingIntent = 
          PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent,
          PendingIntent.FLAG_NO_CREATE);
if (pendingIntent != null) {
    pendingIntent.cancel();
}