在咱们看来二者效果都是同样的,其实看下源码就知道cancel确定会去调dismiss的,若是调用的cancel的话就能够监听DialogInterface.OnCancelListener。android
/** * Cancel the dialog. This is essentially the same as calling {@link #dismiss()}, but it will * also call your {@link DialogInterface.OnCancelListener} (if registered). */ public void cancel() { if (!mCanceled && mCancelMessage != null) { mCanceled = true; // Obtain a new message so this dialog can be re-used Message.obtain(mCancelMessage).sendToTarget(); } dismiss(); }
dismiss能够在任何线程调用,可是最好不要覆写dismiss方法,实在须要就在onStop里去override。ide
/** * Dismiss this dialog, removing it from the screen. This method can be * invoked safely from any thread. Note that you should not override this * method to do cleanup when the dialog is dismissed, instead implement * that in {@link #onStop}. */ @Override public void dismiss() { if (Looper.myLooper() == mHandler.getLooper()) { dismissDialog(); } else { mHandler.post(mDismissAction); } }
在dismissDialog里调用了onStopoop
void dismissDialog() { if (mDecor == null || !mShowing) { return; } if (mWindow.isDestroyed()) { Log.e(TAG, "Tried to dismissDialog() but the Dialog's window was already destroyed!"); return; } try { mWindowManager.removeViewImmediate(mDecor); } finally { if (mActionMode != null) { mActionMode.finish(); } mDecor = null; mWindow.closeAllPanels(); onStop(); mShowing = false; sendDismissMessage(); } }
补上hide方法,注释上说了hide只是隐藏了对话框并无销毁,若是打算用这方法来灭掉对话框就会出现问题,在Activity销毁的时候就会出现崩溃日志了,由于post
Activity销毁时是须要把对话框都关闭掉的。this
日志以下:spa
android.view.WindowLeaked: Activity com.example.androidtest_progressdialog.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{434557e8 G.E..... R.....ID 0,0-1026,288} that was originally added here线程
再看一下hide里是作什么操做:日志
/** * Hide the dialog, but do not dismiss it. */ public void hide() { if (mDecor != null) { mDecor.setVisibility(View.GONE); } }
能够看出,hide只是把对话框里的DecorView设置为不可见,并无从Window移除掉这个DecorView。code