Android报错:WindowManager$BadTokenException: Unable to add window -- window has already been added(示例代
Posted wansho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 [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(示例代的主要内容,如果未能解决你的问题,请参考以下文章
Android7.1.1系统,Toast的Exception: android.view.WindowManager$BadTokenException解决
Android7.1.1系统,Toast的Exception: android.view.WindowManager$BadTokenException解决
Android7.1.1系统,Toast的Exception: android.view.WindowManager$BadTokenException解决
Android7.1.1系统,Toast的Exception: android.view.WindowManager$BadTokenException解决
Android7.1.1系统,Toast的Exception: android.view.WindowManager$BadTokenException解决