cambunctious cambunctious - 2 months ago 40
Android Question

AlarmManager setExact in Android 5.1

From Optimizing for Doze and App Standby:


Doze is particularly likely to affect activities that AlarmManager
alarms and timers manage, because alarms in Android 5.1 (API level 22)
or lower do not fire when the system is in Doze.

To help with scheduling alarms, Android 6.0 (API level 23) introduces
two new AlarmManager methods: setAndAllowWhileIdle() and
setExactAndAllowWhileIdle(). With these methods, you can set alarms
that will fire even if the device is in Doze.


So what do I do if I need to set an alarm for an exact time, even during Doze, in Android 5.1? Is it not possible?

Here is my code

if (noPreciseTime) {
alarmManager.set(AlarmManager.RTC_WAKEUP, now + interval, pendingIntent)
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent)
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent)
} else {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, time, pendingIntent)
}

Answer

So what do I do if I need to set an alarm for an exact time, even during Doze, in Android 5.1?

Devices running 5.1 do not doze, so you need not worry about that. This

alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent)

will work as expected in 5.1. The newer setExactAndAllowWhileIdle was introduced for use on devices running 6.0+. Your code snippet is ok.

alarms in Android 5.1 (API level 22) or lower do not fire when the system is in Doze

This is a bit of a confusing statement. What they mean to say here is alarms set using the 5.1 or lower API's (like setExact) do not fire when a device is in doze.

Comments