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

        最近在测试项目时,需要添加大量的数据,然后运行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类。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值