Android异常之Unable to add window -- token android.os.BinderProxy@d0f9fcf is not valid;

2023-05-16

        最近在测试项目时,需要添加大量的数据,然后运行App时出现了以下报错,之前遇到过此问题,此次再次遇到,把它记录下来留作记录吧。

android.view.WindowManager$BadTokenException: 
Unable to add window -- token android.os.BinderProxy@d0f9fcf is not valid; is your activity running?
         at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
         at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
         at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
         at android.widget.Toast$TN.handleShow(Toast.java:459)
         at android.widget.Toast$TN$2.handleMessage(Toast.java:342)
         at android.os.Handler.dispatchMessage(Handler.java:102)
         at android.os.Looper.loop(Looper.java:154)
         at android.app.ActivityThread.main(ActivityThread.java:6157)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:802)

        反复测试发现在添加数据后可以稳定复现,通过查看源码发现了此错误提示。

// Since the notification manager service cancels the token right
// after it notifies us to cancel the toast there is an inherent
// race and we may attempt to add a window after the token has been
// invalidated. Let us hedge against that.
try {
    mWM.addView(mView, mParams);
    trySendAccessibilityEvent();
} catch (WindowManager.BadTokenException e) {
    /* ignore */
}

 

        源码中提到令牌会失效,原因应该是7.1系统对Toast的window类型做了超时限制,绑定window token,最长超时时间为3.5s,如果UI这段时间内没有执行完任务,toast.show()内部的handle message得不到执行,系统就会把次toast取消掉,并同时把window token设置为无效,等需要显示时,则抛出此异常。

        直接调用系统的toast,即使try{}catch{}也无法避免报错问题。

        所以要避免这个问题,最好等耗时任务完成后再调用toast。

        亦或者自定义toast类,避开系统的超时限制,不直接调用系统的toast类。

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android异常之Unable to add window -- token android.os.BinderProxy@d0f9fcf is not valid; 的相关文章

随机推荐