Search code examples
javaandroidalarmmanager

AlarmMamanger not accurate


My application has an AlarmManager set up to trigger every 60 seconds. It triggers a fragment which checks the current time and looks up if there is any Event happening at that time in the app's calendar. It was running pretty good until I found out that it skipped one of the events. To check the integrity of the app, I made the fragment write the current time (minutes 0-59) on a text file and see if it does skip any. After carefully digging through the file which was recorded for three days continuously, I found that it does.

47, 48, 50, 50, 51, 52, 54, 54, 55, 56, 57, 58, 59, 0, 1, 2,

This happens randomly anywhere. It happens after 3-4 hours. Here's another example

1, 1, 3, 4, 5, 6, 7, 7, 9, 9, 10, 11, 12, 13,

The AlarmManager code doesn't have any problems it seems. Although if the code is skipping a minute OR triggering before the given time has passed there is something wrong somewhere. Here is the code I am using on the AlarmManager

long alertTime = new GregorianCalendar().getTimeInMillis();

    int timeInterval = 60*1000;

    Intent alertIntent = new Intent(this, AlertRec.class);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, timeInterval, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));

Questions: 1) Why is the AlarmManager acting irregularly? 2) How can this be avoided?

Can I reduce the interval time to get around this ? I read the 60 is the minimum interval you need to apply.


Solution

  • According to documentation here: http://developer.android.com/reference/android/app/AlarmManager.html

    Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

    This pretty much explains most of it. Also, as far as I know, they have internally added a minimum time limit for repeating alarms ~1min so reducing the interval might not be the best idea.

    Hope this helps!