Unable to add window — token null is not for an application錯誤的解決方案

來源:互聯網
上載者:User

      今天自己做一個小程式,給windowManager添加一個view的時候,一直報一個錯誤:

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

這個錯誤意思就是 token為空白,所以添加不上view,我在網上查相關資訊,他們說傳入的context對象有問題,但是我反覆測試在activity中啟動widnow並且添加view是正常的,難道就不能在發起一個廣播啟動windowManager並且添加view?

 

如果是添加view出錯,那就說明應該是windowManager.layoutParams中應該缺少什麼參數,結果我在網上查閱了一下,真的是需要在windowManager.layoutParams中添加一些type的,結果自己實驗了一下,結果真的可以了 ,具體的代碼如下:

 

 

/** * @author spring sky * Email vipa1888@163.com * My Name: 石明政 * QQ 840950105 * @param height  高度 * @param width   寬度 * @return */private LayoutParams getLayoutParam(int height,int width){if(wmParam==null){//為windowManager.layoutParams添加type和flag,這樣發送廣播才不會出現token is null這樣的錯誤wmParam = new WindowManager.LayoutParams(-1, 4);  wmParam.windowAnimations = 0;wmParam.format = PixelFormat.TRANSLUCENT| WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW;}wmParam.height = height;wmParam.width = width;return wmParam;}

 

 

這樣,在windowManager中添加view就可以了,還有一種,就是設定彈出框,需要傳入本身的activity.this這個context!

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.