今天自己做一個小程式,給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!