异常:android.view.WindowManager$BadTokenException: Unable to add window — token android.os.BinderProxy@438e7108 is not valid; is your activity running?

因为使用了AsyncTask 异步线程在线程完成以后的onPostExecute方法里面弹出窗口。

这个时候如果用户在onPostExecute调用之间按了返回按钮,activity已经onDestory了,
那么就会报出android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4479b390 is not valid; is your activity running?

解决方法一在弹出窗口之前用Activity的isFinishing判断一下Activity是否还存在:

protected void onPostExecute(Object result) {       if (!isFinishing()) {           showDialog(MY_DIALOG_ID);       }   }  


解决方法二在show的时候捕获一下异常


以下是测试验证
运行这个小程序 默数4的时候按返回 如果不加异常捕获或者判断isFinish的话会崩溃。

public class DialogTestActivity extends Activity {       @Override      public void onCreate(Bundle savedInstanceState) {           super.onCreate(savedInstanceState);           setContentView(R.layout.main);           new Task().execute();         }         private class Task extends AsyncTask<Void, Void, Void> {             @Override          protected Void doInBackground(Void... params) {               try {                   Thread.sleep(5000);               } catch (InterruptedException e) {                   e.printStackTrace();               }               return null;           }             @Override          protected void onPostExecute(Void result) {               super.onPostExecute(result);               //if (!isFinishing()) {                   //try {                       createAlertDialog().show();                   //} catch (Exception e) {                   //}               //}           }         }         private AlertDialog createAlertDialog() {           return new AlertDialog.Builder(DialogTestActivity.this).setTitle("fadfasdf")                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {                       public void onClick(DialogInterface dialog, int whichButton) {                         }                   }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {                       public void onClick(DialogInterface dialog, int whichButton) {                         }                   }).create();       }   }  


转自:http://dingbuoyi.iteye.com/blog/1555030#comments

更多:http://dimitar.me/android-displaying-dialogs-from-background-threads/



更多相关文章

  1. [置顶] Android(安卓)多点触摸 multi-touch
  2. binder机制底层驱动浅析
  3. Android防止用户快速点击
  4. Android(安卓)点击事件的写法
  5. Android(安卓)Studio 实现一个简单的计算器APP
  6. Only the original thread that created a view hierarchy can t
  7. 记录app端嵌入式H5页面
  8. java多线程断点续传
  9. Android开发之侧拉栏的使用

随机推荐

  1. 【Android自学笔记】为Android应用程序添
  2. Android RecyclerView网格布局的学习
  3. [置顶] Android 通过经纬度获取地理位置
  4. android设置一个图片为全屏大小
  5. 07文本处理工具和正则表达式
  6. Android 永久隐藏导航栏,系统栏的方法
  7. 2种方式进行Spinner数据的添加
  8. Android Ble开发出现的问题
  9. android 查看MD5认证指纹
  10. android 自定义商城app价格正序倒序控件