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.
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 PendingIntent
s 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();
}
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