Home » Android » android – AlarmManager For API 17 & 19

android – AlarmManager For API 17 & 19

Posted by: admin June 15, 2020 Leave a comment


I have the following code which will call my intend ‘Alarm Receiver’ every hour to perform a check

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");

    PendingIntent broadcast = PendingIntent.getBroadcast(context,100,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar cal = Calendar.getInstance();
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);

And this works great for Android API 19+ (Android 4.4)

However I want to allow Android API 17 (4.2) to be able to use my app as not everyone can get 4.4 on their phones

The problem is the setExact which is not supported by API 17

Is there a way of calling the Intent to be called which is supported by API 17+ or would I have to somehow find out what verison of android is running and perform one piece of code or another?


How to&Answers:

The way that AlarmManager works was changed in API level 19 to help save battery life. It was so that events could be batched. What this means is that set() and setRepeating() will be inexact on API 19+.

In API versions before 19, you can just use set, which will schedule an alarm for the exact time.

Unfortunately this means that you’ll need to add a check in your code to make sure that you use the correct method for setting an exact alarm:

private void setSingleExactAlarm(long time, PendingIntent pIntent) {
    if (android.os.Build.VERSION.SDK_INT >= 19) {
        mAlarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pIntent);
    } else {
        mAlarmManager.set(AlarmManager.RTC_WAKEUP, time, pIntent);

Additionally, it would be worth reading about Doze that was introduced in Marshmallow and decide how you want your app to work alongside it.


If you want to trigger an exact alarm you should use something like this:

if (android.os.Build.VERSION.SDK_INT >= 19) {
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, NEXT_TIME_IN_MILLISECONDS, operation);
} else {
    alarmManager.set(AlarmManager.RTC_WAKEUP, NEXT_TIME_IN_MILLISECONDS, operation);

Take into account things have changed in Android 6 with doze feature so feel free to check this documentation


You better use AlarmManagerCompat.setExact(…), it handles alarm settings for backwar compatibility and any API Version. For example:

AlarmManagerCompat.setExact(alarmManager, AlarmManager.RTC_WAKEUP, NEXT_TIME_IN_MILLISECONDS, operation);