1. 程式人生 > >Activiy或者Fragment 銷燬時,Dialog 的正確Dismiss方式和測試方法

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.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();
}