0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Farshad
  • 3,074
  • 2
  • 30
  • 44

3 Answers3

2

Why are you not using

protected void onPause();

to fire there

pi.cancel();
alarmManager.cancel(pi);
loretoparisi
  • 15,724
  • 11
  • 102
  • 146
  • 1
    Thanks for response my friend, I get what you are suggesting and of course is right, but the problem was my interpretation about SLEEP ! – Farshad Apr 13 '16 at 00:03
1

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?

Community
  • 1
  • 1
Scott Merritt
  • 1,284
  • 2
  • 13
  • 24
0

The documentation you cite is just saying that the alarm won't fire when the device goes to sleep when ELAPSED_REALTIME is used.

Sounds like you want the alarm to fire when the application process is still alive. You might look at using ActivityLicecycleCallbacks: http://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks.html

This will let you schedule/cancel the alarm based on the process lifecycle as opposed to a single activity.

You might also look at

Application.onTrimMemory

to see when it gets called by the OS. You might find some use cancelling your alarm there.

Coder Roadie
  • 838
  • 1
  • 8
  • 11