我想从 Web 视图中的 JAvascript 启用或禁用 screen_on 功能。
这就是我尝试做的事情
@JavascriptInterface
fun setScreenOn(screenOn: Boolean) {
val window = m_Activity.window
if (screenOn) {
Log.d("screen", "addFlag")
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
Log.d("screen", "clearFlag")
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
不幸的是,这给了我一个 Java 异常。
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Expected: main Calling: JavaBridge
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:11023)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:2473)
at android.view.View.requestLayout(View.java:28020)
at android.view.View.setLayoutParams(View.java:20530)
at android.view.WindowManagerGlobal.updateViewLayout(WindowManagerGlobal.java:464)
at android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:165)
at android.app.Activity.onWindowAttributesChanged(Activity.java:4364)
at android.view.Window.dispatchWindowAttributesChanged(Window.java:1323)
at com.android.internal.policy.PhoneWindow.dispatchWindowAttributesChanged(PhoneWindow.java:3193)
at android.view.Window.setFlags(Window.java:1309)
at android.view.Window.clearFlags(Window.java:1283)
Only the original thread that created a view hierarchy can touch its views.
这是否意味着无法从 Javascript 更改 FLAG_KEEP_SCREEN_ON
?或者有什么办法可以解决这个问题吗?
这是一个常见问题。 Android 限制您从其他线程访问 UI 线程以防止错误。
你可以使用
runOnUiThread(() -> {
val window = m_Activity.window
if (screenOn) {
Log.d("screen", "addFlag")
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
Log.d("screen", "clearFlag")
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
});
以便从任何地方更新用户界面