Android问题集锦之五十:not attached to window manager

not attached to window manager有许多场景发生,下面说下Dialog的dismiss引发的崩溃。

场景复现:

1、异步任务或其他后台线程操作,界面显示滚动条。
两个Tab页快速点击切换,有一定几率出现上述问题引起的崩溃。

java.lang.IllegalArgumentException: View not attached to window manager
    at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:356)
    at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:201)
    at android.view.Window$LocalWindowManager.removeView(Window.java:400)
    at android.app.Dialog.dismissDialog(Dialog.java:268)
    at android.app.Dialog.access$000(Dialog.java:69)
    at android.app.Dialog$1.run(Dialog.java:103)
    at android.app.Dialog.dismiss(Dialog.java:252)
    at xxx.onPostExecute(xxx$1.java:xxx)

2、有些机型上就是会偶现这个问题,着实让人头疼。

解决方案

1、直接try catch,将崩溃阻止

 try {
        if ((this.mDialog != null) && this.mDialog.isShowing()) {
            this.mDialog.dismiss();
        }
    } catch (final IllegalArgumentException e) {
        // Handle or log or ignore
    } catch (final Exception e) {
        // Handle or log or ignore
    } finally {
        this.mDialog = null;
    }  

虽然暴力,但只少不崩溃了。
2、判断创建该Dialog的上下文是否有效,在有效的情况才关闭Dialog。

public void hideProgress() {
    if(mProgressDialog != null) {
        if(mProgressDialog.isShowing()) { //check if dialog is showing.

            //get the Context object that was used to great the dialog
            Context context = ((ContextWrapper)mProgressDialog.getContext()).getBaseContext();

            //if the Context used here was an activity AND it hasn't been finished or destroyed
            //then dismiss it
            if(context instanceof Activity) { 
                if(!((Activity)context).isFinishing() && !((Activity)context).isDestroyed()) 
                    mProgressDialog.dismiss();
            } else //if the Context used wasnt an Activity, then dismiss it too
                mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }
}

下面简写的判断无效的方法:

private boolean isInvalidContext (){  

    return (isDestroyed() || isFinishing());

    }  

参考

1、http://stackoverflow.com/questions/2745061/java-lang-illegalargumentexception-view-not-attached-to-window-manager
2、http://blog.csdn.net/yuxiaohui78/article/details/38076447

你可能感兴趣的:(Android,Android问题集锦)