Rashad.Z
Rashad.Z

Reputation: 2604

AlarmManager triggering after 5 minutes and not at the desired time

I am using an alarm manager to trigger an intent service every 40 seconds. The below code is how I am triggering the alarm and starting the service. I know that the alarm is not always triggered after 40 seconds exactly and may vary.

But I got a case where the alarm varied a lot and stayed constantly triggering EXACTLY every 5 minutes.

starting the alarm:

Intent alarmIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long interval = 40000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

alarm receiver:

@Override
public void onReceive(Context arg0, Intent arg1)
{
     globalVariables.DebugLogging("IsSignedIn: "+GlobalVariables.IsSignedIn+" -DownloadServiceCanStart:- "+GlobalVariables.DownloadServiceCanStart);
     if(GlobalVariables.IsSignedIn)
     {
          if (GlobalVariables.DownloadServiceCanStart)
          {
               GlobalVariables.DownloadServiceCanStart=false;
               Intent intent = new Intent(arg0, DownloadService.class);
               context.startService(intent);
          }
     }
}

Upvotes: 3

Views: 2783

Answers (1)

Knossos
Knossos

Reputation: 16068

The AlarmManager is not very precise.

As the official documentation states:

Note: 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.

There is also a minimum interval of 60 seconds. So your 40 second interval would be expanded to 60 seconds.

If you want to run something every 40 seconds exactly, you could investigate this answer: https://stackoverflow.com/a/9539579/503508

Upvotes: 1

Related Questions