Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep android device from sleeping while plugged in

I'd like to keep the screen on whenever one of my Activities are running and the phone is plugged in to a power source. I know that Wakelocks are tricky, so I'm looking for an example or some documentation on how to accomplish this specific goal.

like image 970
twk Avatar asked Dec 05 '22 01:12

twk


2 Answers

Don't use wake locks for this -- just set and clear the window flag WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON based on whether the device is currently plugged in. You can set the flag with Activity.getWindow().addFlags().

So the code would be

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
like image 125
hackbod Avatar answered Dec 21 '22 09:12

hackbod


A WakeLockisn't that tricky, just make sure to check that it isn't already held when you call acquire() and make sure it is held when you call release(). You also want to make sure you have the android.permission.WAKE_LOCK permission defined in your manifest file.

If you only want to acquire the WakeLock when the phone is plugged in, you can register a BroadcastReceiver that watches for the android.intent.action.ACTION_POWER_CONNECTED and android.intent.action.ACTION_POWER_DISCONNECTED intents. I haven't used these myself, so there may be some application permission you need to get before these intents will actually work.

like image 39
Aaron C Avatar answered Dec 21 '22 09:12

Aaron C