views:

139

answers:

3

I’m doing an application that listens to the android.intent.action.SCREEN_OFF in a Service (if that matter) and then it is supposed to wait a few seconds and launch an action, I’ve tried a timer schedule method, thread and handler postDelay method but all of them seems to fail, they are never executed on a device, it seems like it’s being freezed/killed after phone is locked. It works on emulator and on device attached to USB, but never with device working on battery only, which actually is a main scenario.

Do you know any solutions to this?

A: 

chances are you have your phone set so that when it is plugged in, it never actually locks or sleeps (its one of the developer settings) and imagine the emulator behaves the same way. so you will either have to override the phone's lock settings or change your method. the general rule is that when the screen shuts off, your activity ends.

mtmurdock
including background threads too?
michael
A: 

I cannot test this now (not near my Android device at the moment), but...

Does the broadcast receiver fire at all?

If so, right as you get called, you will need to grab a partial Wake Lock so the CPU stays awake until the timer fires.

Dre
Actually I think I'm doing something wrong with a WakeLock. It doesn't seems to work, I'm acquiring it after a screen_off action is send, so actually the system is already down, could it be a reason?
michael
A: 

A partial wake lock keeps the CPU running, so you should acquire it inside your broadcast receiver for screen_off, and release it after you're done with whatever you're doing. When you're plugged into the USB, the CPU stays on to service the USB connection (in fact, the usb stuff in the kernel holds its own wake lock).

And to answer your other question, yes, even background threads. As soon as everyone is done handling the screen_off broadcast, the CPU is turned off, and you won't run again until someone turns the CPU back on.

joeo