首页 > 代码库 > Android报错:WindowManager$BadTokenException: Unable to add window -- window has already been added

Android报错:WindowManager$BadTokenException: Unable to add window -- window has already been added

很久之前测试通过的代码,现在手机升级了Android7.0后一运行就崩溃,报出这样的错误,具体错误如下:

Process: com.example.sho.android_anti_theft, PID: 26807            
android.view.WindowManager$BadTokenException: Unable to add window -- window android.view.ViewRootImpl$W@363f7b1 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 android.view.ViewRootImpl$W@363f7b1 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