0

I'm working on an app based on programming alarms with AlarmManager.setAlarmClock method. It mainly works, but in some cases alarms are thrown at a wrong time.

For instance, in a Samsung device with android 5.1, I set 3 alarms at:

  • 18:00
  • 22:00
  • 6:00 (next day)

And the result is

  • 18:00 -> Ok
  • 18:15 -> Thrown at 18:15
  • 6:00 -> Thrown at 2:00!!

Here is the code for setting the alarm:

if (Build.VERSION.SDK_INT >= 21) {
        Log.d(TAG, "Final (idle) at " + sdf.format(calendarObj.getTime()));
        AlarmManager.AlarmClockInfo info = new AlarmManager.AlarmClockInfo(calendarObj.getTimeInMillis(), pendingIntent);
        alarmManager.setAlarmClock(info, pendingIntent);
    }

And this is the code to generate the "calendarObj" instances (the iqDate object is an object with a specific Date, and the three alarms are set based on the date of this object. Just ignore it):

Calendar c1 = Calendar.getInstance();
c1.setTime(iqDate.getTime());
c1.add(Calendar.DAY_OF_MONTH, -1);
c1.set(Calendar.HOUR_OF_DAY, 18);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);

Calendar c3 = Calendar.getInstance();
c3.setTime(iqDate.getTime());
c3.add(Calendar.DAY_OF_MONTH, -1);
c3.set(Calendar.HOUR_OF_DAY, 22);
c3.set(Calendar.MINUTE, 0);
c3.set(Calendar.SECOND, 0);

Calendar c7 = Calendar.getInstance();
c7.setTime(iqDate.getTime());
c7.set(Calendar.MINUTE, 0);
c7.set(Calendar.SECOND, 0);
c7.set(Calendar.HOUR_OF_DAY, 6);

Any ideas why this is happening? It works most of the times, but sometimes alarms are not working properly...

Thanks!

  • And please avoid suggestions as changing to "setExact" or "setExactAndAllowWhileIdle", because I've tried and they don't work as I need. Thanks! – Quim Motger May 14 '18 at 07:43

1 Answers1

0

Beginning with API 19 (android.os.Build.VERSION_CODES.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,android.app.PendingIntent) and setExact(int,long,android.app.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.

leo
  • 1
  • 1