Search code examples
androidtimeralarmmanagerandroid-4.4-kitkat

Accurate Timers on Android APIs 15 and higher


I'm in the process of updating a customer's application and have hit a problem with the timer mechanism they have adopted. Previously they had been using AlarmManager.setRepeating to create an alarm which recurs after a specified interval.

AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);    
mgr.setRepeating(
        AlarmManager.ELAPSED_REALTIME_WAKEUP, 
        SystemClock.elapsedRealtime() + interval, 
        interval, 
        pi
);

As of Android 4.4 this results in inaccurate timings, so I tried to replace this with an exact timer.

mgr.setExact(
        AlarmManager.ELAPSED_REALTIME_WAKEUP, 
        SystemClock.elapsedRealtime() + interval, 
        pi
);

However setExact is only available from API 19. Currently MinSDK is set to 15 and Target to 21. While I believe that I could simply set the minimum API to be 19, the customer would still like to support devices runnning APIs 15-18.

Is there any way to support both processes, using setRepeating on API 15-18, then setExact on 19+?

EDIT: Is anything lost by dropping the target API from 21 to 18, and would this fix the problem?


Solution

  • You can get version of the installed os with Build.VERSION.SDK_INT (Retrieving Android API version programmatically)

    if (Build.VERSION.SDK_INT >= 19)
        mgr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, pi);
    else if (Build.VERSION.SDK_INT >= 15)
        mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval, interval, pi);