调试小技巧:Activity 销毁后 Dialog dismiss 崩溃

问题的解决方法很简单,这里主要是介绍一个调试小技巧,且听事件由来:

场景:Activity 中弹出一个 Dialog,几秒后会 dismiss。平时测试没遇到崩溃,但是崩溃平台却捕捉到如下错误:

java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{41ef97f8 V.E..... R.....ID 0,0-480,762} not attached to window manager
    at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:370)
    at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:299)
    at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:84)
    at android.app.Dialog.dismissDialog(Dialog.java:329)
    at android.app.Dialog.dismiss(Dialog.java:312)
    at com.quickdy.vpn.dialog.b.dismiss(ConnectingDialog.java:229)
    at com.quickdy.vpn.dialog.b.i(ConnectingDialog.java:436)
    at com.quickdy.vpn.dialog.b.j(ConnectingDialog.java:59)
    at com.quickdy.vpn.dialog.b$a.onFinish(ConnectingDialog.java:262)
    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5584)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
    at dalvik.system.NativeStart.main(Native Method)

原因就是 Dialog dismiss 的时候, Activity 的窗口已经被干掉了。
在 stackoverflow 上有人提了这个奇技淫巧:

1. Enable this option on your device: Settings -> Developer Options - Don't keep Activities.
2. Press Home button while the AsyncTask is executing and the ProgressDialog is showing.

这样就能模拟『对话框展示过程中,Activity 被销毁的情况』。

解决办法:在 Activity / Fragment 的 onDestroy 方法,加上这几行代码:

@Override
protected void onDestroy() {
    if (dialog != null && dialog.isShowing()) {
        dialog.dismiss();
    }
    super.onDestroy();
}

你可能感兴趣的:(调试小技巧:Activity 销毁后 Dialog dismiss 崩溃)