android view WindowManager BadTokenException is your ac

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

               

这是由于activity的view还没有渲染完成, 就调用了与该View相关的方法, 会如下异常 : 

After publishing one of our apps on Google Play market I started receiving strange exception on Play Console:android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@40b47bd8 is not valid; is your activity running?at android.view.ViewRoot.setView(ViewRoot.java:452)at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:283)at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:193)at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:118)at android.view.Window$LocalWindowManager.addView(Window.java:532)at android.app.Dialog.show(Dialog.java:269)...This exception occurred while app was trying to notify user from the background thread by opening a Dialog.I could not reproduce it myself: I tried every device I had and every type of emulator I could think of, but no luck, the app worked just fine. However, according to Google Play console, exception occurred very often and seemed very consistent.After doing some research I found out that it is possible for my app to try notifying the user while being in the background (device screen is locked, app is sent to background with home button).So I looked at Android docs on Activity and discovered a very useful method – isFinishing() which is called by Android when Activity enters finishing stage: be it explicit finish() call or activity clean up made by Android.Using that flag it is very easy to avoid opening dialog from background thread when Activity is finishing:runOnUiThread(new Runnable() {   @Override   public void run() if(!isFinishing()){  showDialog (           new AlertDialog.Builder(MainActivity.this)    .setTitle(R.string.dialogTitle)    .setMessage(R.string.dialogText)    .setCancelable(false)    .setPositiveButton(R.string.txtOk,     new OnClickListener() {     @Override     public void onClick(DialogInterface dialog, int which) {                                          // whatever...           }    })    .create()        );    }   }}); As you can see – the fix is very simple and straightforward: just check if your Activity is going to finish before opening dialog.


或者 : 

new Handler().postDelayed(new Runnable() {    public void run() {        // 你的相关代码    }}, 100);


或者 : 

findViewById(R.id.main_page_layout).post(new Runnable() {   public void run() {     // 你的相关代码   }});



           

分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值