Search code examples
androidalarmmanager

How to prevent triggering alarm when screen is off?


I'm trying to trigger the alarm in a specific interval only when the device is awake, This is the code which I used to achieve this:

AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime(),
                INTERVAL_ONE_MINUTE,
                pi);

Considering documentations about AlarmManager.ELAPSED_REALTIME android is not supposed to trigger the alarm when device screen is off (If I mistake not)

Alarm time in SystemClock.elapsedRealtime() (time since boot, including sleep). This alarm does not wake the device up; if it goes off while the device is asleep, it will not be delivered until the next time the device wakes up

Contrary to my expectation alarm was triggered by system when the screen is off, Am I missing something here?


Solution

  • When they speak of the device going to sleep, that doesn't mean the screen is off.

    See: When does android device go to sleep mode?

    See: http://developer.android.com/training/scheduling/wakelock.html

    When the device's screen isn't on, it still will be woken up to do things from time to time. To save battery, it'll sleep, but apps will inevitably wake it up to do things.

    You could check to see if the screen is on: How can I tell if the screen is on in android?