android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@4

android.view.WindowManager$BadTokenException: Unable to add window – token android.os.BinderProxy@438e7108 is not valid; is your activity running?
解决:子Activity启动dialog(或类似操作)引发此错误
解决方法:
AlertDialog.Builder(xxx.this) => AlertDialog.Builder(this.getParent())
或(this)改为(xxx.this)

其他处理方法:
解决方法一在弹出窗口之前用Activity的isFinishing判断一下Activity是否还存在
Java代码 收藏代码
protected void onPostExecute(Object result) {
if (!isFinishing()) {
showDialog(MY_DIALOG_ID);
}
}

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

以下是测试验证
运行这个小程序 默数4的时候按返回 如果不加异常捕获或者判断isFinish的话会崩溃。
Java代码 收藏代码
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();  
}  

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值