理解Window和WindowManager(二)--Window的内部机制

Window是一个抽象的概念,每一个Window都对应着一个View和一个ViewRootImplWindow和View通过ViewRootImpl来建立联系,Window是以View的形式存在。

Window的添加过程

Window的添加过程需要通过WindowManager的addView来实现,WindowManager是一个接口,它的实现类是WindowManagerImpl

WindowManagerImpl # addView()

WindowManagerImpl工作模式是桥接模式,将所有操作全部委托给WindowManagerGlobal来实现

    // WindowManagerGlobal以单例模式的形式向外提供自己的实例
    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        // 全部交给了WindowManagerGlobal来处理
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

WindowManagerGlobal四个全局集合

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>();
// 调用了removeView()但是删除操作还未完成的View对象
private final ArraySet<View> mDyingViews = new ArraySet<View>();

WindowManagerGlobal # addView()

    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        // 1.检查参数合法性,如果是子Window还需要调整一些布局参数
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (display == null) {
            throw new IllegalArgumentException("display must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }

        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
        // 如果有父Window,根据type赋值params的title和token
        if (parentWindow != null) {
            parentWindow.adjustLayoutParamsForSubWindow(wparams);
        } else {
            // If there's no parent, then hardware acceleration for this view is
            // set from the application's hardware acceleration setting.
            // 如果没有并且应用开启了硬件加速,就设置该Window开启硬件加速
            final Context context = view.getContext();
            if (context != null
                    && (context.getApplicationInfo().flags
                            & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            // Start watching for system property changes.
            if (mSystemPropertyUpdater == null) {
                // 遍历更新所有ViewRootImpl的有关参数
                mSystemPropertyUpdater = new Runnable() {
                    @Override public void run() {
                        synchronized (mLock) {
                            for (int i = mRoots.size() - 1; i >= 0; --i) {
                                mRoots.get(i).loadSystemProperties();
                            }
                        }
                    }
                };
                // 添加到执行队列中
                SystemProperties.addChangeCallback(mSystemPropertyUpdater);
            }
            // 看需要添加的View是否已经在mViews中
            int index = findViewLocked(view, false);
            // 被添加
            if (index >= 0) {
                // 在死亡队列中存在
                if (mDyingViews.contains(view)) {
                    // Don't wait for MSG_DIE to make it's way through root's queue.
                    // 将这个View移除
                    mRoots.get(index).doDie();
                } else {
                    // 否则说明View已经添加过了不需要重新添加
                    throw new IllegalStateException("View " + view
                            + " has already been added to the window manager.");
                }
                // The previous removeView() had not completed executing. Now it has.
            }

            // If this is a panel window, then find the window it is being
            // attached to for future reference.
            // 如果属于子Window层级
            if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                    wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
                final int count = mViews.size();
                //  遍历ViewRootImpl,看是否存在一个Window的IBinder对象和需要添加的Window的token一致,之后赋值引用
                for (int i = 0; i < count; i++) {
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                        panelParentView = mViews.get(i);
                    }
                }
            }
            
            // 2.新创建一个ViewRootImpl
            root = new ViewRootImpl(view.getContext(), display);
            // 给需要添加的view设置params
            view.setLayoutParams(wparams);
            // 将三个参数加入三个集合中
            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);

            // do this last because it fires off messages to start doing things
            try {
                // 调用ViewRootImpl的setView()
                root.setView(view, wparams, panelParentView);
            } catch (RuntimeException e) {
                // BadTokenException or InvalidDisplayException, clean up.
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
                throw e;
            }
        }
    }

ViewRootImpl # setView()

3.通过ViewRootImpl来更新界面并完成Window的添加过程

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    synchronized (this) {
        if (mView == null) {
            // ......
            mAdded = true;
            int res;
            // 内部调用提交一个更新界面的Runnable去执行performTraversals()
            requestLayout();
            // ......
            try {
                mOrigWindowType = mWindowAttributes.type;
                mAttachInfo.mRecomputeGlobalAttributes = true;
                collectViewAttributes();
                // 通过WindowSession完成Window的添加过程(一次IPC调用)
                // mWindowSession的类型是IWindowSession(它是一个Binder对象,真正的实现类是Session)
                res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                        getHostVisibility(), mDisplay.getDisplayId(),
                        mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                        mAttachInfo.mOutsets, mInputChannel);
            } // ......
        }
    }
}

Session # addToDisplay()

内部通过WindowManagerService(它的内部会为每一个应用保留一个单独的Session)来实现Window的添加

    @Override
    public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
            Rect outOutsets, InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outStableInsets, outOutsets, outInputChannel);
    }

Window的删除过程

也是先通过WindowManagerImpl后再进一步通过WindowManagerGlobal来实现的。WindowManager接口提供了两种删除方法removeView和removeViewImmediate,分别表示异步删除和同步删除

WindowManagerGlobal # removeView()

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

        synchronized (mLock) {
            // 找到待删除的View的索引
            int index = findViewLocked(view, true);
            View curView = mRoots.get(index).getView();
            // 做进一步的删除
            removeViewLocked(index, immediate);
            if (curView == view) {
                return;
            }
            // 抛出异常,删除的View不是Window的顶级View
            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());
            }
        }
        // 调用ViewRootImpl的die()去删除
        // immediate参数表示是否使用同步删除,false为异步删除
        boolean deferred = root.die(immediate);
        if (view != null) {
            view.assignParent(null);
            if (deferred) {
                // mDyingViews表示待删除的View列表
                mDyingViews.add(view);
            }
        }
    }

ViewRootImpl # die()

在异步删除的情况下,只是发送了一个请求删除的消息后就立刻返回,这个时候View并没有完成删除操作。

    boolean die(boolean immediate) {
        // Make sure we do execute immediately if we are in the middle of a traversal or the damage
        // done by dispatchDetachedFromWindow will cause havoc on return.
        // 如果是同步删除也没执行performTraversals()
        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());
        }
        // 发送一个MSG_DIE的消息
        mHandler.sendEmptyMessage(MSG_DIE);
        return true;
    }

Handler会处理此消息并调用doDie()方法

@Override
public void handleMessage(Message msg) {
    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) {
                // 真正删除View
                dispatchDetachedFromWindow();
            }
            ...
            mAdded = false;
        }
        
        WindowManagerGlobal.getInstance().doRemoveView(this);
    }

ViewRootImpl # dispatchDetachedFromWindow()

主要做了这些事情:

  • 调用View的dispatchDetachedFromWindow()方法,内部会调用View的onDetachedFromWindow()以及DetachedFromWindowInternal()
  • 移除回调,清除数据和消息
  • 远程调用WindowManagerService的removeWindow()
  • 切断通信通道
  • 移除performTraversals()的runnable
    void dispatchDetachedFromWindow() {
        mFirstInputStage.onDetachedFromWindow();
        if (mView != null && mView.mAttachInfo != null) {
            // 调用监听的onXXX()回调方法
            mAttachInfo.mTreeObserver.dispatchOnWindowAttachedChange(false);
            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 {
            // IPC过程,会调用WindowManagerService的removeWindow方法
            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);
        // 移除消息队列中准备执行performTraversals()的runnable
        unscheduleTraversals();
    }

WindowManagerGlobal # doRemoveView()

在调用dispatchDetachedFromWindow()删除完成后调用这个方法,将Window所关联的对象从列表中删除

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

Window的更新过程

WindowManagerGlobal # updateViewLayout()

    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }
        
        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams)params;
        // 更新View的LayoutParams
        view.setLayoutParams(wparams);

        synchronized (mLock) {
            int index = findViewLocked(view, true);
            ViewRootImpl root = mRoots.get(index);
            mParams.remove(index);
            mParams.add(index, wparams);
            // 更新ViewRootImpl中的LayoutParams
            root.setLayoutParams(wparams, false);
        }
    }

ViewRootImpl # setLayoutParams()

void setLayoutParams(WindowManager.LayoutParams attrs, boolean newView) {
    synchronized (this) {
        ...
        
        // 复制赋值参数
        mWindowAttributesChangesFlag = mWindowAttributes.copyFrom(attrs);
        
        ...
        
        mWindowAttributesChanged = true;
        // 调用performTraversals()
        scheduleTraversals();
    }
}

在performTraversals()中除了调用三大流程,还有这一行:
最终调用WindowManagerService的relayoutWindow(),同样是个IPC过程

relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值