Since the release of Android Lollipop 5.0 (API21), there is now an API to officially show/hide the alarm icon. There is more information about this here on stackoverflow.
Thanks to it, I managed to now display the alarm icon on 5.0+ Android devices. Unfortunately, I can't dismiss/hide/cancel the icon if the alarm is disabled.
Here is what I'm doing (a mix of several attempts from Stackoverflow and Android stock alarm) :
public static void setNextAlert(final Context context) {
final Alarm alarm = calculateNextAlert(context);
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);
int flags = alarm == null ? PendingIntent.FLAG_NO_CREATE : 0;
PendingIntent operation = PendingIntent.getBroadcast(context, 0 /* requestCode */, intent, flags);
if (alarm != null)
{
if(UtilsAlarm.isLollipopOrLater())
{
PendingIntent viewIntent = PendingIntent.getActivity(context, alarm.id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(alarm.time, viewIntent);
am.setAlarmClock(info, operation);
}
else
{
if(UtilsAlarm.isKitKatOrLater())
{
am.setExact(AlarmManager.RTC_WAKEUP, alarm.time, sender);
}
else
{
am.set(AlarmManager.RTC_WAKEUP, alarm.time, sender);
}
setStatusBarIcon(context, true);
}
Calendar c = Calendar.getInstance();
c.setTimeInMillis(alarm.time);
String timeString = formatDayAndTime(context, c);
saveNextAlarm(context, timeString);
}
else
{
if(UtilsAlarm.isLollipopOrLater())
{
am.cancel(operation);
}
else
{
am.cancel(sender);
setStatusBarIcon(context, false);
}
saveNextAlarm(context, "");
}
Intent i = new Intent(NEXT_ALARM_TIME_SET);
context.sendBroadcast(i); }
So if we're on a version lower to Lollipop, it is still working great. However, for Lollipop devices, the icon is displayed when an alarm is enabled but if you disable it (and there are no other alarms enabled), it is currently cancelled from the next coming alarm (expected result) but the icon is still present on the notification bar.
Anyone has an idea of the issue?
Thansk for your help.