Android弹窗组件工作机制之Dialog、DialogFragment(二)

二、Dialog的消失

1、dismiss

private final Runnable mDismissAction = this::dismissDialog;

public void dismiss() {
    if (Looper.myLooper() == mHandler.getLooper()) {
        dismissDialog();
    } else {
        mHandler.post(mDismissAction);
    }
}

保证UI操作都在主线程执行,而且引用了Java8新特性写法this::dismissDialog,最后都会调用dismissDialog()

2、dismissDialog

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 {
        //这里移除DecorView
        mWindowManager.removeViewImmediate(mDecor);
    } finally {
        if (mActionMode != null) {
            mActionMode.finish();
        }
        mDecor = null;
        mWindow.closeAllPanels();
        onStop();
        mShowing = false;
 
        sendDismissMessage();
    }
}

从show中知道,我们将DecorView加入到WindowManager中去,所以这里移除的是DecorView

3、WindowManagerImpl.removeViewImmediate

public void removeViewImmediate(View view) {
    //委托给mGlobal来进行实现
    mGlobal.removeView(view, true);
}

同样的交给WindowManagerGlobal去处理

4、WindowManagerGlobal.removeView

public void removeView(View view, boolean immediate) {
    if (view == null) {
        throw new IllegalArgumentException("view must not be null");
    }
 
    synchronized (mLock) {
        //待remove view的索引
        int index = findViewLocked(view, true);
        //mRoots保存着每一个viewRootImpl对象
        View curView = mRoots.get(index).getView();
        //真正对view进行了remove操作
        removeViewLocked(index, immediate);
        if (curView == view) {
            return;
        }
 
        throw new IllegalStateException("Calling with view " + view
                + " but the ViewAncestor is attached to " + curView);
    }
}

找到对应要移除的View后进行View逻辑处理工作

5、WindowManagerGlobal.removeViewLocked

private void removeViewLocked(int index, boolean immediate) {
    ViewRootImpl root = mRoots.get(index);
    View view = root.getView();
 
    if (view != null) {
        InputMethodManager imm = InputMethodManager.getInstance();
        if (imm != null) {
            imm.windowDismissed(mViews.get(index).getWindowToken());
        }
    }
    //重点在ViewRootImpl中的die方法中
    boolean deferred = root.die(immediate);
    if (view != null) {
        view.assignParent(null);
        if (deferred) {
            mDyingViews.add(view);
        }
    }
}

找到对应的ViewRootImpl,进行移除并释放工作

6、ViewRootImpl.die

boolean die(boolean immediate) {
    if (immediate && !mIsInTraversal) {
        //继续跟踪
        doDie();
        return false;
    }
 
    if (!mIsDrawing) {
        destroyHardwareRenderer();
    } else {
        Log.e(TAG, "Attempting to destroy the window while drawing!\n" +
                "  window=" + this + ", title=" + mWindowAttributes.getTitle());
    }
    mHandler.sendEmptyMessage(MSG_DIE);
    return true;
}

7、ViewRootImpl.doDie

void doDie() {
    checkThread();
    if (LOCAL_LOGV) Log.v(TAG, "DIE in " + this + " of " + mSurface);
    synchronized (this) {
        if (mRemoved) {
            return;
        }
        mRemoved = true;
        if (mAdded) {
            //这里是真正移除Dialog的View
            dispatchDetachedFromWindow();
        }
 
        if (mAdded && !mFirst) {
            //硬件渲染destroy
            destroyHardwareRenderer();
 
            if (mView != null) {
                int viewVisibility = mView.getVisibility();
                boolean viewVisibilityChanged = mViewVisibility != viewVisibility;
                if (mWindowAttributesChanged || viewVisibilityChanged) {
                    // If layout params have been changed, first give them
                    // to the window manager to make sure it has the correct
                    // animation info.
                    try {
                        if ((relayoutWindow(mWindowAttributes, viewVisibility, false)
                                & WindowManagerGlobal.RELAYOUT_RES_FIRST_TIME) != 0) {
                            mWindowSession.finishDrawing(mWindow);
                        }
                    } catch (RemoteException e) {
                    }
                }
                //Surface的释放
                mSurface.release();
            }
        }
 
        mAdded = false;
    }
    //移除之前存储的变量
    WindowManagerGlobal.getInstance().doRemoveView(this);
}

保证线程安全后,做移除和释放工作

8、WindowManagerGlobal.doRemoveView

一般程序最后的工作都是释放工作,移除之前存储的变量

void doRemoveView(ViewRootImpl root) {
    synchronized (mLock) {
        final int index = mRoots.indexOf(root);
        if (index >= 0) {
            //释放工作
            mRoots.remove(index);
            mParams.remove(index);
            final View view = mViews.remove(index);
            mDyingViews.remove(view);
        }
    }
    if (HardwareRenderer.sTrimForeground && HardwareRenderer.isAvailable()) {
        doTrimForeground();
    }
}

9、ViewRootImpl.dispatchDetachedFromWindow

void dispatchDetachedFromWindow() {
    if (mView != null && mView.mAttachInfo != null) {
        mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
        //此方法会回调onDetachedFromWindow方法,会做资源的回收
        mView.dispatchDetachedFromWindow();
    }
 
    mAccessibilityInteractionConnectionManager.ensureNoConnection();
    mAccessibilityManager.removeAccessibilityStateChangeListener(
            mAccessibilityInteractionConnectionManager);
    mAccessibilityManager.removeHighTextContrastStateChangeListener(
            mHighContrastTextManager);
    removeSendWindowContentChangedCallback();
 
    destroyHardwareRenderer();
 
    setAccessibilityFocus(null, null);
 
    mView.assignParent(null);
    mView = null;
    mAttachInfo.mRootView = null;
 
    mSurface.release();
 
    if (mInputQueueCallback != null && mInputQueue != null) {
        mInputQueueCallback.onInputQueueDestroyed(mInputQueue);
        mInputQueue.dispose();
        mInputQueueCallback = null;
        mInputQueue = null;
    }
    if (mInputEventReceiver != null) {
        mInputEventReceiver.dispose();
        mInputEventReceiver = null;
    }
    try {
        //这里调用了mWindowSession的remove方法,在WindowManagerService层通过IPC机制完成真正的window删除
       mWindowSession.remove(mWindow);
    } catch (RemoteException e) {
    }
 
    // Dispose the input channel after removing the window so the Window Manager
    // doesn't interpret the input channel being closed as an abnormal termination.
    if (mInputChannel != null) {
        mInputChannel.dispose();
        mInputChannel = null;
    }
 
    mDisplayManager.unregisterDisplayListener(mDisplayListener);
 
    unscheduleTraversals();
}

到最后会和添加View的时候完成闭环,还是通过WindowSession的IPC机制去调用的,最后在WindowManagerService层通过IPC机制去实现的

总结

1.Dialog的dismiss和show形成闭环,调用的过程是相似的,只不过多了资源的释放环节

Android弹窗组件工作机制之Dialog、DialogFragment(二)_第1张图片

DialogFragment

DialogFragment本身继承自Fragment

public class DialogFragment extends Fragment
        implements DialogInterface.OnCancelListener, DialogInterface.OnDismissListener

在平时中,我们需要自定义WeDialogFragment,而且在正式开发中踩过的坑:

  • 需要对参数进行onSaveInstanceState操作,这类操作主要是防止异步吊起DialogFragment报nullPoint的Bug
  • 需要重写show(),对show做一层弹出时候的保护,这类操作主要是防止异步吊起DialogFragment报onSaveInstanceState的Bug
public class WeDialogFragment extends DialogFragment {

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_TITLE, title);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.WeDialog);
        
        if (savedInstanceState != null) {
            title = savedInstanceState.getString(BUNDLE_TITLE);
        }
    }
    
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCanceledOnTouchOutside(true);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.getWindow().setWindowAnimations(R.style.DialogAnimation);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        return dialog;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.view_fragment_dialog, container, false);
    }
    
    @Override
    public void show(FragmentManager manager, String tag) {
        if (!manager.isStateSaved()) {
            super.show(manager, tag);
        }
    }
}

然后在Activity中弹出DialogFragment

WeDialogFragment weDialogFragment = new WeDialogFragment();
weDialogFragment.show(activity.getSupportFragmentManager(),"weDialogFragment");       

一、DialogFragment的显示

1、DialogFragment.show

public void show(FragmentManager manager, String tag) {
    mDismissed = false;
    mShownByMe = true;
    FragmentTransaction ft = manager.beginTransaction();
    ft.add(this, tag);
    ft.commit();
}

show的方法其实就是对Fragment的处理,将Fragment添加到Fragment栈中

二、DialogFragment的隐藏

1、DialogFragment.dismiss

public void dismiss() {
    dismissInternal(false);
}

public void dismissAllowingStateLoss() {
    dismissInternal(true);
}

void dismissInternal(boolean allowStateLoss) {
    if (mDismissed) {
        return;
    }
    mDismissed = true;
    mShownByMe = false;
    if (mDialog != null) {
        mDialog.dismiss();
    }
    mViewDestroyed = true;
    if (mBackStackId >= 0) {
        getFragmentManager().popBackStack(mBackStackId,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
        mBackStackId = -1;
    } else {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.remove(this);
        if (allowStateLoss) {
            ft.commitAllowingStateLoss();
        } else {
            ft.commit();
        }
    }
}

dismiss的方法也是对Fragment的处理,将Fragment移除到Fragment栈中

三、Dialog的创建

1、DialogFragment.onCreateDialog

@NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new Dialog(getActivity(), getTheme());
}

和创建普通的Dialog没什么区别,我们重写该方法,可以自定义弹出AlertDialog等其他自定义Dialog

四、Dialog的视图

1、DialogFragment.onActivityCreated

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (!mShowsDialog) {
        return;
    }

    //拿到的就是onCreateView返回值的view对象,具体可以在Fragment源码找到
    View view = getView();
    if (view != null) {
        if (view.getParent() != null) {
            throw new IllegalStateException(
                    "DialogFragment can not be attached to a container view");
        }
        //真正设置view
        mDialog.setContentView(view);
    }
    final Activity activity = getActivity();
    if (activity != null) {
        mDialog.setOwnerActivity(activity);
    }
    mDialog.setCancelable(mCancelable);
    mDialog.setOnCancelListener(this);
    mDialog.setOnDismissListener(this);
    if (savedInstanceState != null) {
        Bundle dialogState = savedInstanceState.getBundle(SAVED_DIALOG_STATE_TAG);
        if (dialogState != null) {
            mDialog.onRestoreInstanceState(dialogState);
        }
    }
}

在Activity创建的时候,Fragment的周期会回调onActivityCreated,从而对Dialog设置视图

五、Dialog的显示隐藏

Dialog显示隐藏就简单了,随着Fragment的生命周期显示和隐藏,直接看代码就行了

@Override
public void onStart() {
    super.onStart();
    if (mDialog != null) {
        mViewDestroyed = false;
        mDialog.show();
    }
}

@Override
public void onStop() {
    super.onStop();
    if (mDialog != null) {
        mDialog.hide();
    }
}

总结

DialogFragment = Fragment + Dialog,DialogFragment本身继承Fragment,Fragment只是用来依附在Activity上,可以监听Activity的生命周期,从而去通知Dialog做对应的操作,而Dialog才是我们正在显示在屏幕上的弹窗,而非一个Fragment。这里的Dialog真正显示出来的View是从onCreateView()中获取view后,在源码中调用dialog的setContentView()显示出来的

你可能感兴趣的:(Android弹窗组件工作机制之Dialog、DialogFragment(二))