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.
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);
A WakeLock
isn'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With