Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to check if alarm has been set by AlarmManager

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.

like image 769
Kevin Richards Avatar asked Jun 05 '15 16:06

Kevin Richards


1 Answers

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();
}
like image 147
David Wasser Avatar answered Oct 20 '22 15:10

David Wasser