Reputation: 1130
In my app, I need to make sure the android device's screen stays on when the user clicks a button. When the use clicks another button, I want to allow the screen to turn off when it normally would. To do this, I need to call:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
The android documentation states that this call must be made from an activity, which is what I've done. Here is my code snippet:
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);
}
}
}
When I run this code on my Samsung Galaxy S5 and S6, I get an exception. The code to keep the screen on works when I run it natively in android studio, so that's not the issue. Any idea how to get this functionality to work? wake lock will not work because I need to enable and disable this functionality based on UI events.
Upvotes: 1
Views: 608
Reputation: 45476
If you check the exception (./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)
the message Only the original thread that created a view hierarchy can touch its views
will give you enough information. If you check this question, you just need to move your code to the main thread:
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);
}
});
Upvotes: 0