Android 后台线程弹对话框导致程序崩溃(is not valid; is your activity running)

来源:互联网 发布:2017商务笔记本 知乎 编辑:程序博客网 时间:2024/05/07 14:02

异常: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是否还存在:

[java] view plaincopy
  1. protected void onPostExecute(Object result) {     
  2.     if (!isFinishing()) {     
  3.         showDialog(MY_DIALOG_ID);     
  4.     }     
  5. }    


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


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

[java] view plaincopy
  1. public class DialogTestActivity extends Activity {     
  2.     @Override    
  3.     public void onCreate(Bundle savedInstanceState) {     
  4.         super.onCreate(savedInstanceState);     
  5.         setContentView(R.layout.main);     
  6.         new Task().execute();     
  7.     
  8.     }     
  9.     
  10.     private class Task extends AsyncTask<Void, Void, Void> {     
  11.     
  12.         @Override    
  13.         protected Void doInBackground(Void... params) {     
  14.             try {     
  15.                 Thread.sleep(5000);     
  16.             } catch (InterruptedException e) {     
  17.                 e.printStackTrace();     
  18.             }     
  19.             return null;     
  20.         }     
  21.     
  22.         @Override    
  23.         protected void onPostExecute(Void result) {     
  24.             super.onPostExecute(result);     
  25.             //if (!isFinishing()) {     
  26.                 //try {     
  27.                     createAlertDialog().show();     
  28.                 //} catch (Exception e) {     
  29.                 //}     
  30.             //}     
  31.         }     
  32.     
  33.     }     
  34.     
  35.     private AlertDialog createAlertDialog() {     
  36.         return new AlertDialog.Builder(DialogTestActivity.this).setTitle("fadfasdf")     
  37.                 .setPositiveButton("OK"new DialogInterface.OnClickListener() {     
  38.                     public void onClick(DialogInterface dialog, int whichButton) {     
  39.     
  40.                     }     
  41.                 }).setNegativeButton("Cancel"new DialogInterface.OnClickListener() {     
  42.                     public void onClick(DialogInterface dialog, int whichButton) {     
  43.     
  44.                     }     
  45.                 }).create();     
  46.     }     
  47. }   
0 0