简体   繁体   English

如何在插入时保持Android设备不被睡眠

[英]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. 我知道Wakelocks很棘手,所以我正在寻找一个关于如何实现这个特定目标的示例或文档。

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() . 不要为此使用唤醒锁 - 只需根据设备当前是否插入来设置和清除窗口标志WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON 。您可以使用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() . 一个WakeLock是不是靠谱,只需确保检查时你怎么称呼它尚未持有acquire()并确保当你调用它举行release() You also want to make sure you have the android.permission.WAKE_LOCK permission defined in your manifest file. 您还需要确保在清单文件中定义了android.permission.WAKE_LOCK权限。

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. 如果你只想在插入手机时获得WakeLock,你可以注册一个BroadcastReceiver ,它监视android.intent.action.ACTION_POWER_CONNECTEDandroid.intent.action.ACTION_POWER_DISCONNECTED意图。 I haven't used these myself, so there may be some application permission you need to get before these intents will actually work. 我自己没有使用过这些,因此在这些意图实际工作之前,您可能需要获得一些应用程序权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM