android.view.WindowManager$BadTokenException: Unable to add window - token andr

android.view.WindowManager$BadTokenException: Unable to add window -- token andr因为使用了AsyncTask

android.view.WindowManager$BadTokenException: Unable to add window -- token andr
因为使用了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是否还存在

public class DialogTestActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);new Task().execute();}private class Task extends AsyncTask<Void, Void, Void> {@Overrideprotected Void doInBackground(Void... params) {try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}return null;}@Overrideprotected 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();}}