Android开发经验谈Android开发源码原理知识点

Dialog 源码分析

2020-04-17  本文已影响0人  折剑游侠

分析下Dialog源码,忽略一些细节,只扣重点。

Dialog构造方法
    private final WindowManager mWindowManager;
    final Window mWindow;
    private final Handler mHandler = new Handler();
    private final Runnable mDismissAction = this::dismissDialog;

    public Dialog(@NonNull Context context) {
        this(context, 0, true);
    }

    public Dialog(@NonNull Context context, @StyleRes int themeResId) {
        this(context, themeResId, true);
    }

    //最终都会调用此构造方法
    Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
        if (createContextThemeWrapper) {
            if (themeResId == 0) {
                final TypedValue outValue = new TypedValue();
                context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
                themeResId = outValue.resourceId;
            }
            mContext = new ContextThemeWrapper(context, themeResId);
        } else {
            mContext = context;
        }

        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        //初始化Window实例PhoneWindow
        final Window w = new PhoneWindow(mContext);
        mWindow = w;
        w.setCallback(this);
        w.setOnWindowDismissedCallback(this);
        //初始化WindowManager实例WindowManagerImpl
        w.setWindowManager(mWindowManager, null, null);
        w.setGravity(Gravity.CENTER);

        mListenersHandler = new ListenersHandler(this);
    }
Window.setWindowManager()
    public void setWindowManager(WindowManager wm, IBinder appToken, String appName) {
        setWindowManager(wm, appToken, appName, false);
    }

    public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        ...
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }
Dialog.show()
    public void show() {
        //showing状态,显示DecorView
        if (mShowing) {
            if (mDecor != null) {
                if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
                    mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
                }
                mDecor.setVisibility(View.VISIBLE);
            }
            return;
        }
        ...
        //初始化DecorView
        mDecor = mWindow.getDecorView();
        ...
        WindowManager.LayoutParams l = mWindow.getAttributes();
        if ((l.softInputMode
                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
            WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
            nl.copyFrom(l);
            nl.softInputMode |=
                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
            l = nl;
        }
      
        //重点
        mWindowManager.addView(mDecor, l);
        mShowing = true;

        sendShowMessage();
    }

WindowManager.addView()流程前面讲过Android Activity、Window、View
简而言之,经过一系列调用,最终调用到ViewRootImpl.performTraversals()开启绘制流程,显示View。

Dialog.hide()
    public void hide() {
        if (mDecor != null) {
            mDecor.setVisibility(View.GONE);
        }
    }

hide()和show()方法通过顶层View-DecorView的Visibility属性,显示隐藏。

Dialog.dismiss()
    public void dismiss() {
        //主线程直接关闭
        if (Looper.myLooper() == mHandler.getLooper()) {
            dismissDialog();
        } else {//子线程调用handler.post()发送一个带有Runnable消息切换到主线程
            mHandler.post(mDismissAction);
        }
    }
mDismissAction调用到dismissDialog()
    private final Runnable mDismissAction = this::dismissDialog;
Dialog.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 {
            //重点
            mWindowManager.removeViewImmediate(mDecor);
        } finally {
            if (mActionMode != null) {
                mActionMode.finish();
            }
            mDecor = null;
            mWindow.closeAllPanels();
            onStop();
            mShowing = false;

            sendDismissMessage();
        }
    }

前面只分析过WindowManager.addView()
这里继续分析WindowManager.removeView()

WindowManagerImpl.removeViewImmediate()
    @Override
    public void removeView(View view) {
        mGlobal.removeView(view, false);
    }

    public void removeViewImmediate(View view) {
        mGlobal.removeView(view, true);
    }
WindowManagerGlobal.removeView()
    public void removeView(View view, boolean immediate) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }

        synchronized (mLock) {
            int index = findViewLocked(view, true);
            View curView = mRoots.get(index).getView();
            removeViewLocked(index, immediate);
            if (curView == view) {
                return;
            }

            throw new IllegalStateException("Calling with view " + view
                    + " but the ViewAncestor is attached to " + curView);
        }
    }
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());
            }
        }
        boolean deferred = root.die(immediate);
        if (view != null) {
            view.assignParent(null);
            if (deferred) {
                mDyingViews.add(view);
            }
        }
    }
ViewRootImpl.die()

immediate:
WindowManagerImpl.removeView()传的false
WindowManagerImpl.removeViewImmediate()传的true
true:ViewRootImpl.die()直接调用ViewRootImpl.doDie()
false:ViewRootImpl.die()通过handler发送消息,在主线程事件循环中调用ViewRootImpl.doDie()有一定的延迟。

    boolean die(boolean immediate) {
        if (immediate && !mIsInTraversal) {
            doDie();
            return false;
        }

        if (!mIsDrawing) {
            destroyHardwareRenderer();
        } else {
            Log.e(mTag, "Attempting to destroy the window while drawing!\n" +
                    "  window=" + this + ", title=" + mWindowAttributes.getTitle());
        }
        //mHandler是ViewRootHandler
        mHandler.sendEmptyMessage(MSG_DIE);
        return true;
    }
ViewRootHandler.handleMessage()
switch (msg.what) {
        ...
        case MSG_DIE:
                doDie();
                break;
}
ViewRootImpl.doDie()
    void doDie() {
        //主线程判断
        checkThread();
        if (LOCAL_LOGV) Log.v(mTag, "DIE in " + this + " of " + mSurface);
        synchronized (this) {
            if (mRemoved) {
                return;
            }
            mRemoved = true;
            if (mAdded) {
                //解除与Window的关联
                dispatchDetachedFromWindow();
            }

            if (mAdded && !mFirst) {
                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) {
                        }
                    }

                    mSurface.release();
                }
            }

            mAdded = false;
        }
        WindowManagerGlobal.getInstance().doRemoveView(this);
    }
WindowManagerGlobal.doRemoveView()
    private final ArrayList<View> mViews = new ArrayList<View>();
    private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();
    private final ArrayList<WindowManager.LayoutParams> mParams =
            new ArrayList<WindowManager.LayoutParams>();
    private final ArraySet<View> mDyingViews = new ArraySet<View>();

    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 (ThreadedRenderer.sTrimForeground && ThreadedRenderer.isAvailable()) {
            doTrimForeground();
        }
    }

将保存的View相关数据从对应的数组中移除

上一篇下一篇

猜你喜欢

热点阅读