WindowManager.addView() 导致 BadTokenException
WindowManager.addView() causes BadTokenException
我正在尝试创建叠加层 window,但是当我尝试将视图添加到 WindowManager 时,出现异常。我添加了 "SYSTEM_ALERT_WINDOW" 权限,并在应用信息中启用了 "Draw over other apps"。我是从服务的 onCreate 函数中调用它的。
- 设备:模拟器运行8.0.0
- 目标 SDK 和已编译 SDK 版本:26
- AppCompat 版本:26.0.0
代码:
WindowManager manager = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout overlay = (RelativeLayout) inflater.inflate(R.layout.button_main, null);
final WindowManager.LayoutParams params =
new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
0,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 0;
manager.addView(overlay, params);
异常堆栈跟踪:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:764
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
无论我为 LayoutParams 使用什么类型,我总是遇到这个崩溃。
使用TYPE_APPLICATION_OVERLAY。它是 Android O 允许显示在其他应用程序之上的唯一 window 类型。
查看此内容以获得解释:https://developer.android.com/preview/behavior-changes.html#cwt
我正在尝试创建叠加层 window,但是当我尝试将视图添加到 WindowManager 时,出现异常。我添加了 "SYSTEM_ALERT_WINDOW" 权限,并在应用信息中启用了 "Draw over other apps"。我是从服务的 onCreate 函数中调用它的。
- 设备:模拟器运行8.0.0
- 目标 SDK 和已编译 SDK 版本:26
- AppCompat 版本:26.0.0
代码:
WindowManager manager = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
RelativeLayout overlay = (RelativeLayout) inflater.inflate(R.layout.button_main, null);
final WindowManager.LayoutParams params =
new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
0,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 0;
manager.addView(overlay, params);
异常堆栈跟踪:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:764
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
无论我为 LayoutParams 使用什么类型,我总是遇到这个崩溃。
使用TYPE_APPLICATION_OVERLAY。它是 Android O 允许显示在其他应用程序之上的唯一 window 类型。
查看此内容以获得解释:https://developer.android.com/preview/behavior-changes.html#cwt