2

There is a code which supposed to trigger an action at a specified precise time using the AlarmManager (the next day at 7:00am):

val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, FooIntentService::class.java)
val pendingIntent = PendingIntent.getService(this, 0, intent, 0)

// Set alarm
val calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.set(Calendar.HOUR_OF_DAY, 7)
calendar.set(Calendar.MINUTE, 0)

// Set tomorrow
calendar.add(Calendar.DATE, 1)

manager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

I have tested this code to trigger event in up to 5 minutes from now, closing the app (close all apps) and putting it on sleep (pressing Hold button) - and it works. Yet when I set the time for tomorrow at 7:00am (which is way more then 5 minutes from now) - it would never trigger, until I have unblocked it (woke up manually). At the moment I woke it up - the action triggered right away.


Question: is the example code I have provided correct for setting planned event in my case?

dedda1994
  • 151
  • 1
  • 15
0leg
  • 13,464
  • 16
  • 70
  • 94
  • 2
    Maybe doze: https://stackoverflow.com/questions/35629268/alarm-manager-issue-in-android-6-0-doze-mode – Alex Jul 07 '17 at 06:36
  • @Alex Thank you for sharing, that might be the answer. I will investigate and provide the result in this thread. – 0leg Jul 07 '17 at 06:38
  • 1
    Take a look at the 2nd part of the following answer: https://stackoverflow.com/a/39739886/3363481 – earthw0rmjim Jul 07 '17 at 06:44

1 Answers1

2

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.

From documentation

Basically, the alarm is intended not exact to minimize wakeups and battery use. You can replace set with setExact then it should work as you required.

manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent);
Joshua
  • 5,901
  • 2
  • 32
  • 52