How to keep CPU from 'sleeping' when screen is turned off in Android?

fatfreddyscat picture fatfreddyscat · Oct 1, 2011 · Viewed 14.1k times · Source

I have an application in which I am sending network data over WiFI. Everything is fine until I turn the display off or the device goes to 'sleep'. I'm already locking the WiFi however, it seems to be the case that the CPU speed ramps down when in sleep which causes my streaming to not behave properly (i.e. packets don't flow as fast as I would like as they do when the device is not sleeping).

I know that I possibly can/possibly should address this at the protocol level however, that might possibly not be possible as well...

Is there any way to "prevent the CPU from going to 'sleep' when the screen is off"? If so, how? If not, any advice on how to keep the speed of my WiFi stream consistent whether the device is in sleep mode or not?

Answer

Michael Madsen picture Michael Madsen · Oct 1, 2011

Grab a PARTIAL_WAKE_LOCK from the PowerManager. You'll also need to add the WAKE_LOCK permission to your manifest.

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag"); 
wl.acquire();
//do what you need to do
wl.release();