有没有办法限制 Android 上 FLAG_KEEP_SCREEN_ON 屏幕打开的时间?

Is there a way to limit the time the screen is on with FLAG_KEEP_SCREEN_ON on Android?

我不想使用唤醒锁。 有没有一种简单的方法可以使用 FLAG_KEEP_SCREEN_ON

来限制屏幕打开的时间

如果您在此处阅读文档:docs

比你看到的你不需要关心这个。 但是你可以看到:

Note: You don't need to clear the FLAG_KEEP_SCREEN_ON flag unless you no longer want the screen to stay on in your running application (for example, if you want the screen to time out after a certain period of inactivity). The window manager takes care of ensuring that the right things happen when the app goes into the background or returns to the foreground. But if you want to explicitly clear the flag and thereby allow the screen to turn off again, use clearFlags(): getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON).

您可以将它与处理程序上的 Runnable, post delayed 结合使用, 这是 Android 的方式,或者使用 TimerTask,这将是 更多 Java 方式。

示例:

    final long FIVE_MINUTES = 1000*60*5;
    Handler handler = new Handler();

    final Runnable r = new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    };

    handler.postDelayed(r, FIVE_MINUTES);

希望对您有所帮助。