decorview that was originally added here or java.lang.IllegalArgumentException: View not attached to window manager
使用Dialog的时候,没少出现下面这两个报错
12-11 17:47:49.776: E/WindowManager(11461): android.view.WindowLeaked: Activity TestActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42204800 V.E..... R.....I. 0,0-640,164} that was originally added here
12-11 17:47:50.666: E/AndroidRuntime(11461): java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{42204800 V.E..... R.....I. 0,0-640,164} not attached to window manager
其原因就是:Dialog生命周期比Activity的生命周期长
所以,出现这个bug的时候,请检查创建这个Dialog的context所属的Activity是不是已经结束了,而dialog还在显示。
下面的测试代码可以复现上面提到的bug
public class TestActivity extends Activity{ private Dialog mDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); mDialog = new Dialog(this); mDialog.show(); finish();//直接结束这个Activity,此时Dialog没有关闭,还在显示,生命周期比Activity长了,就会出现上面提到的Bug }
解决方法:
1.请检查,是否还未等Dialog消失就提前结束Activity。如果是,肯定是你的逻辑出问题了,还没等Dialog结束就结束Activity。
2.不管什么情况,Activity一结束,确实要关闭Dialog。那么可在onStop或者onPause里面关闭dialog
@Override protected void onStop() { super.onStop(); if(mDialog.isShowing()){ mDialog.dismiss(); } }