Activiy或者Fragment 销毁时,Dialog 的正确Dismiss方式和测试方法

 
  

场景:Activity或者Fragment 中弹出一个 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..dialog.b.dismiss(ConnectingDialog.java:229)
    at com.quickdy..dialog.b.i(ConnectingDialog.java:436)
    at com.quickdy..dialog.b.j(ConnectingDialog.java:59)
    at com.quickdy..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();
}

你可能感兴趣的:(android,日常问题,android,bug)