Search code examples
androidalarmmanagerandroid-alarms

Using AlarmManager With Different APIs


From my understanding, if I wish to create an exact repeating alarm (regardless if the device is in idle mode or not) using the AlarmManager Class, I am required to use a different scheme depending on the Android version installed. As per my readings, I would need to use setRepeating with RTC_WAKEUP for an API up to 18, setExact with manual re-scheduling RTC_WAKEUP for an API between 19 and 22, and finally setExactAndAllowWhileIdle with manual re-scheduling for an API >= to 23.

  1. How should I handle all cases? Should I verify the API version and then program the Alarm accordingly?

  2. Or is there a Support Library I could use for backward compatibility, which would work for all scenarios?

  3. If I am required to use the first alternative above, how do I cancel the Alarms? Do I need to use a similar scheme, in which I would verify the API version used, and have different code executed for the cancellation, corresponding to the API installed?


Solution

  • How should I handle all cases? Should I verify the API version and then program the Alarm accordingly?

    If you wanted, you could use set() on pre-19 versions of Android and keep the manual rescheduling consistent for all versions, rather than using manual rescheduling on some and automatic scheduling on others.

    Also note that on Android P, I would expect even setExactAndAllowWhileIdle() to not be exact, if your app falls into a non-Active app standby bucket.

    Or is there a Support Library I could use for backward compatibility, which would work for all scenarios?

    There is AlarmManagerCompat, which offers a backwards-compatible implementation of setExactAndAllowWhileIdle().

    how do I cancel the Alarms? Do I need to use a similar scheme, in which I would verify the API version used, and have different code executed for the cancellation, corresponding to the API installed?

    Since you cancel by PendingIntent, you would only need different cancellation logic if you use different PendingIntent structures. My guess is that you could use the same PendingIntent for all scenarios, in which case your cancel() logic would be the same for all scenarios.