Adam
Adam

Reputation: 957

Prevent alarm from going off when device is asleep

I've set a repeating alarm that I only want going off when the device is awake. When it's asleep, I want it to stop (and come back on when the device wakes up). However, it's currently going off no matter what. Here's how I register my alarm:

    Intent updateIntent = new Intent(UPDATE_INTENT);
    AlarmManager alarmService = (AlarmManager) context.getSystemService(
            Context.ALARM_SERVICE);
    PendingIntent updatePendingIntent = PendingIntent.getBroadcast(context, 0,
            updateIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmService.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(), UPDATE_INTERVAL, updatePendingIntent);

The alarm manager docs say that RTC will not wake up the device. The docs specify exactly the behavior that I want:

Alarm time in System.currentTimeMillis() (wall clock time in UTC). 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.

When I press the lock button on the device, I clearly see the going to sleep message from PowerManager in logcat:

I/PowerManagerService(488): Going to sleep by user request...

And then my alarm goes off anyway. What's going on here?

Ironically, every other question I've found on SO deals with alarms NOT going off while the device is asleep. I wish I had their problem!!

Upvotes: 0

Views: 213

Answers (2)

Adam
Adam

Reputation: 957

I eventually decided to register broadcast receivers to listen for SCREEN_ON, and SCREEN_OFF, and toggle the alarm appropriately. I realize this might not be super elegant, but at least it always works even if another app is holding a wake lock.

Listening for screen on and off: android: broadcast receiver for screen on and screen off

Turning off an alarm: How to stop an alarm in android

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007296

However, it's currently going off no matter what.

Presumably something else is holding a partial WakeLock, and the device is not actually asleep, even though the screen may be off. Use adb shell dumpsys power to try to track it down (look for the "Wake Locks" section).

Upvotes: 1

Related Questions