Android報錯:WindowManager$BadTokenException: Unable to add window -- window has already been added

來源:互聯網
上載者:User

標籤:cti   manager   flags   申請   oop   view   rgba   logs   ras   

很久之前測試通過的代碼,現在手機升級了Android7.0後一運行就崩潰,報出這樣的錯誤,具體錯誤如下:

Process: com.example.sho.android_anti_theft, PID: 26807            
android.view.WindowManager$BadTokenException: Unable to add window -- window [email protected] has already been added at android.view.ViewRootImpl.setView(ViewRootImpl.java:691) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94) at android.widget.Toast$TN.handleShow(Toast.java:434) at android.widget.Toast$TN$2.handleMessage(Toast.java:345) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

從報錯資訊中,我得出這樣一個結論:

在Android6.0以前,使用windowManager添加一個懸浮窗時,我使用的懸浮窗類型是TYPE_TOAST,即
params.type = WindowManager.LayoutParams.TYPE_TOAST;
windowManager.addView(contentView, params);
但是系統升級Android7.0後,就會報ndroid.view.WindowManager$BadTokenException: Unable to add window -- window [email protected] has already been added
的錯,具體意思是Toast已經被添加到視窗中,所以這時候我們可以把TYPE_TOAST換成TYPE_PHONE,這樣就可以顯示懸浮窗了,程式也不會crash。

這裡附上添加懸浮窗的代碼,僅供參考:

WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);WindowManager.LayoutParams params = new     WindowManager.LayoutParams();params.type = WindowManager.LayoutParams.TYPE_PHONE;params.format = PixelFormat.RGBA_8888;params.gravity = Gravity.LEFT | Gravity.TOP;params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;params.width = windowManager.getDefaultDisplay().getWidth();params.height = windowManager.getDefaultDisplay().getHeight();params.x = 0;params.y = 0;windowManager.addView(contentView, params);      //這裡要的contentview需要自己定義,而且添加懸浮窗需要動態申請懸浮窗許可權。

    

Android報錯:WindowManager$BadTokenException: Unable to add window -- window has already been added

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.