Problems with Android’s WakeLock when on battery

For the sake of anyone else who may fall over this one at some point in the future…

I was trying to bring the phone out of sleep periodically using a Timer. That timer executes code that looks something like:

PowerManager pm = (PowerManager) this.ctx.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "FlashNotify");

This worked beautifully when plugged in via the USB debugger, but the moment I took the phone out of the cradle, everything stops. Blast.

It seems that when the phone drops into sleep mode when on battery mode, it enters a deep sleep state, where even the FULL_WAKE_LOCK can’t wake it up. The magic to prevent this – Before the phone makes it to the deep sleep state, grab a PARTIAL_WAKE_LOCK to keep it just about conscious. While this is potentially a little unfriendly on the battery, that’s kind of the point of this application, and we’re only going to do it for a little while.

(Vague conjecture – Maybe the OS is doing something akin to PowerManager.goToSleep to manage this – The API docs say that this overrides any wake locks, which seems a little heavy handed. Maybe that’s just wake locks which are currently active. I could dig around in the Android source, but I frankly can’t be bothered 🙂 )

This remedies the only major problem left with deploying this app now, and it’s currently running full time on my own phone. Just got to hook the settings screen up so that it works properly, and all should be ready to roll 🙂