javafx android FLAG_KEEP_SCREEN_ON

javafx android FLAG_KEEP_SCREEN_ON

在我的应用中,我需要确保 android 设备的屏幕在用户单击按钮时保持打开状态。当用户单击另一个按钮时,我想让屏幕正常关闭。为此,我需要致电: getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

android 文档声明此调用必须从 activity 进行,这就是我所做的。这是我的代码片段:

public class AndroidDataProvider implements DataProvider {
    @Override
    public void keepScreenOn(boolean flag) {
        if(flag) {
            Window window = FXActivity.getInstance().getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
        else {
            Window window = FXActivity.getInstance().getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    }
}

当我在我的 Samsung Galaxy S5 和 S6 上 运行 这段代码时,出现异常。 当我 运行 它在 android studio 中原生时,保持屏幕打开的代码有效,所以这不是问题。知道如何让这个功能发挥作用吗?唤醒锁将不起作用,因为我需要根据 UI 个事件启用和禁用此功能。

如果检查异常(./adb logcat -v threadtime):

AndroidRuntime: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
AndroidRuntime:     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6855)
AndroidRuntime:     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1040)
AndroidRuntime:     at android.view.View.requestLayout(View.java:19657)
AndroidRuntime:     at android.view.View.setLayoutParams(View.java:13247)
AndroidRuntime:     at android.view.WindowManagerGlobal.updateViewLayout(WindowManagerGlobal.java:365)
AndroidRuntime:     at android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:99)
AndroidRuntime:     at android.app.Activity.onWindowAttributesChanged(Activity.java:2867)
AndroidRuntime:     at android.view.Window.dispatchWindowAttributesChanged(Window.java:1098)
AndroidRuntime:     at com.android.internal.policy.PhoneWindow.dispatchWindowAttributesChanged(PhoneWindow.java:2998)
AndroidRuntime:     at android.view.Window.setFlags(Window.java:1075)
AndroidRuntime:     at android.view.Window.addFlags(Window.java:1033)

消息 Only the original thread that created a view hierarchy can touch its views 将为您提供足够的信息。如果你检查这个question,你只需要将你的代码移动到主线程:

    FXActivity.getInstance().runOnUiThread(() -> {
        Window window = FXActivity.getInstance().getWindow();
        if (flag) {
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        } else {
            window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    });