关于Android中windowleaked异常的理解 博客分类: Android_笔记 windowleakedandroiddialogactivity
首先,这是今天遇到的一个问题,应该算是一个小问题吧,下面是我的代码:
saveDiary.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //将新建的游记保存到数据库 ContentValues values = new ContentValues(); values.put("Content", content.getText().toString()); values.put("PicUri", photo_path); values.put("PubDate", getDateString()); values.put("isMarked", 1); //values.put("Latitude", "0.00000");//纬度 //values.put("Longitude", "0.00000");//经度 DButil util = new DButil(NewDiaryActivity.this); util.addDiary(values); //添加成功,给出提示跳转回活动界面 AlertDialog.Builder builder = new AlertDialog.Builder(NewDiaryActivity.this); builder.setTitle("提示") .setMessage("是否将游记同步到微博") .setNegativeButton("不了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).setPositiveButton("好的",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //将游记发布到微博 } }).show(); NewDiaryActivity.this.finish(); } });
所报的异常信息:
07-29 17:08:15.286: E/WindowManager(23935): Activity team.cell.nbtravel.activity.NewDiaryActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f6f3a0 that was originally added here
07-29 17:08:15.286: E/WindowManager(23935): android.view.WindowLeaked: Activity team.cell.nbtravel.activity.NewDiaryActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@44f6f3a0 that was originally added here
解决办法:
首先,我们要知道的是在Android中Dialog(对话框),是异步的,就是程序线程不会等待对话框中的内容执行完成才继续执行下面的代码,而是直接往下走不管对话框中的内容是否已经执行完成。正是因为这种机制,导致了对话框还没显示出来,就调用finish()方法销毁活动时的矛盾,即本文提到的windowleaked异常了。
具体方法,修改代码,将finish()方法的调用放置到dialog.cancel()自后即可:
builder.setTitle("提示") .setMessage("是否将游记同步到微博") .setNegativeButton("不了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); NewDiaryActivity.this.finish(); } }).setPositiveButton("好的",new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //将游记发布到微博 NewDiaryActivity.this.finish(); } }).show();