How to keep android device from sleeping while plugged in

久未见 提交于 2019-12-20 01:34:51

问题


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.


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/3949917/how-to-keep-android-device-from-sleeping-while-plugged-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!