0

我想创建一个覆盖窗口,但是当我尝试添加视图到WindowManager时,它给了我一个例外。我已添加“SYSTEM_ALERT_WINDOW”权限,并已在应用信息中启用“通过其他应用绘制”。我从服务的onCreate函数中调用它。WindowManager.addView()导致BadTokenException

  • 设备:模拟器中运行8.0.0
  • 目标SDK和编译SDK版本:26
  • 程序兼容性版本: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,我总是得到这个崩溃。

回答

0

使用TYPE_APPLICATION_OVERLAY。这是Android O允许在其他应用上显示的唯一窗口类型。

检查了解一下:https://developer.android.com/preview/behavior-changes.html#cwt

+0

谢谢。就是这样!我实际上在无障碍服务中这样做,我想知道为什么TYPE_ACCESSIBILITY_OVERLAY不起作用。 (该服务在设置中作为连接的无障碍服务启用) – ravindu1024

相关问题