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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.