强制屏幕上屏幕上

2023-09-11 11:14:18 作者://一个人的伤心、、

如何强制屏幕保持活跃并没有关闭,而我的应用程序正在运行?

How do I force the screen to stay active and not shut off while my app is running?

推荐答案

这需要你给你的应用程序的其他权限,这是很容易引入错误,你不小心留持有唤醒锁,从而在屏幕上留下。

PLEASE DO NOT USE A WAKE LOCK

This requires that you give your app an additional permission, and it is very easy to introduce bugs where you accidentally remain holding the wake lock and thus leave the screen on.

这是远远不如使用窗口标记 FLAG_KEEP_SCREEN_ON ,您可以在您的活动的窗口,使您的的onCreate()是这样的:

It is far, far better to use the window flag FLAG_KEEP_SCREEN_ON, which you can enable on your activity's window in your onCreate() like this:


    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

这将确保在屏幕上停留,而你的窗口是在前台,只有当它是在前台。它大大简化了这种常见的情况,消除你需要做的是在国家之间您的应用程序转换任何戏法。

This will make sure that the screen stays on while your window is in the foreground, and only while it is in the foreground. It greatly simplifies this common use case, eliminating any juggling you need to do as your app transitions between states.