7

There is this new AlarmManager.setAlarmClock(...) method in API 21, which sets a new alarm and displays a status bar alarm icon.

I use it like this:

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ALARM_ALERT_ACTION);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setAlarmClock(new AlarmManager.AlarmClockInfo(time, sender), sender);

The problem is that I don't know how to cancel this alarm, because this code doesn't work:

am.cancel(PendingIntent.getBroadcast(context, 0, new Intent(ALARM_ALERT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT));

The alarm itself is cancelled (my BroadcastReceiver's onReceive is not called) but the status bar alarm icon is still displayed and also AlarmManager.getNextAlarmClock() returns this alarm.

Smuggler
  • 83
  • 1
  • 7

1 Answers1

13

PendingIntent.FLAG_CANCEL_CURRENT says "cancel the current PendingIntent". That confuses AlarmManager when you go to cancel() it, and a confused AlarmManager is never a good thing.

Only use PendingIntent.FLAG_CANCEL_CURRENT when you have a clear reason to do so. Don't use it as some default, "oh, I'll use this instead of 0, because I like typing in lots of characters" value. :-)

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Furthermore, using the same PendingIntent `sender` for both purposes is unlikely to work right. The `AlarmClockInfo` constructor's `showIntent` argument tells the OS what to do when the user taps on the alarm clock info in the notification drawer or the lock screen. `setAlarmClock()`'s `operation` argument tells AlarmManager what to do when the alarm "goes off." Presumably you should pass the latter to `cancel()`. – Jerry101 Sep 27 '15 at 00:36
  • @CommonsWare, does `PendingIntent.FLAG_NO_CREATE` work this both `AlarmManager.AlarmClockInfo` and `setAlarmClock` ? – Vyacheslav Mar 20 '16 at 06:38
  • @Vyacheslav: `FLAG_NO_CREATE` does not really have anything to do with anything in `AlarmManager` specifically. I suggest that you ask a fresh Stack Overflow question where you explain exactly what your concern is. – CommonsWare Mar 20 '16 at 10:47
  • @CommonsWare , I've already created it: http://stackoverflow.com/questions/36110837/check-if-charged-setalarmclock-of-alarmmanager – Vyacheslav Mar 20 '16 at 12:24