Search code examples
androidserviceandroid-alarms

Android Alarm setExactAndAllowWhileIdle unexpected behavior on Samsung


My android app is running a repeating alarm, using setExactAndAllowWhileIdle on Marshmallow. The alarm occurs every 10s and avoids doze mode by using permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS (device has agreed to ignore battery optimizations for this app)

 public void startAlarm(Intent alarmIntent, int delayMs, int alarmId) {
    PendingIntent recurringAlarm = PendingIntent.getBroadcast(context.getApplicationContext(), alarmId,
            alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Calendar updateTime = Calendar.getInstance();
    alarms.cancel(recurringAlarm);
    if (Build.VERSION.SDK_INT >= 23) {
        alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis() + delayMs, recurringAlarm);
    } else if (Build.VERSION.SDK_INT >= 19) {
        alarms.setExact(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis() + delayMs, recurringAlarm);
    } else {
        alarms.set(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis() + delayMs, recurringAlarm);
    }
}

This alarm starts a service. The service then creates another alarm for 10s time using the same method (above). I presume that this alarm will occur every 10s because doze mode is ignored, but on rare occasions the alarm will be postponed for much longer:

  • 53 minutes 6 seconds
  • 18 minutes 40 seconds
  • 54 minutes 37 minutes 19 seconds
  • 1 day 48 minutes 30 seconds

What could be causing this strange behavior? This only seems to be occurring on a Samsung device.


Solution

  • The official doc states

    To reduce abuse, there are restrictions on how frequently these alarms will go off for a particular application. Under normal system operation, it will not dispatch these alarms more than about every minute (at which point every such pending alarm is dispatched); when in low-power idle modes this duration may be significantly longer, such as 15 minutes.

    I suspect Samsung has made modifications to make this duration even longer than 15 minutes. They are known for making deep reaching modifications, which cause unexpected behaviour more often than not.