我试图创建一个叠加窗口但是当我尝试将视图添加到WindowManager时,它给了我一个例外。我添加了" SYSTEM_ALERT_WINDOW"权限,我已启用"绘制其他应用程序"在应用程序信息。我是在服务的onCreate函数中调用它。
代码:
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,我总是会遇到这种崩溃。
答案 0 :(得分:3)
使用TYPE_APPLICATION_OVERLAY。它是Android O允许在其他应用程序上显示的唯一窗口类型。
请查看此信息以获取解释:https://developer.android.com/preview/behavior-changes.html#cwt