setRepeating() of AlarmManager repeats after 1 minute no matter what the time is set (5 seconds in this case, API 18+)

Nikhil Tambe picture Nikhil Tambe · Jan 4, 2016 · Viewed 14.7k times · Source

I have set the repeat time to 5 seconds. The first toast appears after 5 seconds, but all the next once repeat after 1 minute.
I tried the code with setRepeating() as well, it still doesn't work.
here is my code:

public void constructJob(){

    Intent alertIntent = new Intent(this, AlarmManagerService.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this, 0,
            alertIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(
            AlarmManager.RTC_WAKEUP,
            GregorianCalendar.getInstance().getTimeInMillis(),
            repeatTime(),
            pendingIntent
    );

}

public long repeatTime(){
    return 5000;
}

AlarmManagerService.java

public class AlarmManagerService extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
             Toast.makeText(context, "5 seconds have passed",
                            Toast.LENGTH_SHORT).show();
}

Answer

ctate picture ctate · Jan 21, 2016

The documentation needs to be updated. As of I think Android 5.1 (API version 22) there is a minimum period of 1 minute for repeating alarms, and alarms cannot be set less than 5 seconds in the future.

If you need to do work within one minute, just set the alarm directly, then set the next one from that alarm's handler, etc.

If you need to do work within 5 seconds, post it to a Handler instead of using the alarm manager?