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

相關問題