WindowManagerService第二讲之Window的操作

在第一讲的时候我们说WindowManager类继承于ViewManager,ViewManager是一个接口类。实现了三个方法,对应的分别是窗口的添加、更新、删除。

我们下面对于这三个Window的操作流程来详述。

1.Window的添加

A.ViewManager#addView
public interface ViewManager
{
   
    /**
     * Assign the passed LayoutParams to the passed View and add the view to the window.
     * <p>Throws {@link android.view.WindowManager.BadTokenException} for certain programming
     * errors, such as adding a second view to a window without removing the first view.
     * <p>Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
     * secondary {@link Display} and the specified display can't be found
     * (see {@link android.app.Presentation}).
     * @param view The view to be added to this window.
     * @param params The LayoutParams to assign to view.
     */
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}
B.WindowManagerImpl#addView

WindowManager中没有addView的实现,那么我们需要继续看WindowManager的子类WindowManagerImpl中是否有实现。

    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
   
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }
C.WindowManagerGlobal#addView

第一讲有介绍过WindowManagerImpl和WindowManagerGlobal之间使用桥接模式,WindowManagerImpl中的addView不执行具体的方法,转而在WindowManagerGlobal中实现:

    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
   
        // 1 start
        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;
        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.
            final Context context = view.getContext();
            if (context != null
                    && (context.getApplicationInfo().flags
                            & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
   
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }

        // 1 end
        ViewRootImpl root;
        View panelParentView = null;

        // 2 start
        synchronized (mLock) {
   
            // Start watching for system property changes.
            if (mSystemPropertyUpdater == null) {
   
                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);
            }

            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.
                    mRoots.get(index).doDie();
                } else {
   
                    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.
            if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                    wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
   
                final int count = mViews.size();
                for (int i = 0; i < count; i++) {
   
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
   
                        panelParentView = mViews.get(i);
                    }
                }
            }
            
            // 2 end
            
            // 3 start

            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
            
            // 3 end
            
            // 4 start 

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

注释1:检查传入的参数是否合法;

注释2:检查系统属性值;

注释3:创建一个ViewRootImpl对象,并将window的一系列对象添加到列表中;

注释4:通过ViewRootImpl的setView()方法更新界面,完成window的添加过程;

D.ViewRootImpl#setView
    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
   
        synchronized (this) {
   
            if (mView == null) {
   
                mView = view;

                ......
                mAdded = true;
                int res; /* = WindowManagerImpl.ADD_OKAY; */

                // Schedule the first layout -before- adding to the window
                // manager, to make sure we do the relayout before receiving
                // any other events from the system.
                // 1
                requestLayout();
                if ((mWindowAttributes.inputFeatures
                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
   
                    mInputChannel = new InputChannel();
                }
                mForceDecorViewVisibility = (mWindowAttributes.privateFlags
                        & PRIVATE_FLAG_FORCE_DECOR_VIEW_VISIBILITY) != 0;
                try {
   
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    // 2
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(), mTmpFrame,
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel,
                            mTempInsets);
                    setFrame(mTmpFrame);
                } catch (RemoteException e) {
   
                    mAdded = false;
                    mView = null;
                    mAttachInfo.mRootView = null;
                    mInputChannel = null;
                    mFallbackEventHandler.setView(null);
                    unscheduleTraversals();
                    setAccessibilityFocus(null, null);
                    throw new RuntimeException("Adding window failed", e);
                } finally {
   
                    if (restore) {
   
                        attrs.restore();
                    }
                }

                ......
            }
        }
    }

setView()方法中有很多逻辑,我们截取和window添加有关的部分。

注释1:调用ViewRootImpl的requestLayout()方法,完成异步刷新请求;这个方法最终会调用到ViewRootImpl的scheduleTraversals()方法,这个方法就是View绘制的入口方法。

注释2:调用addToDisplay()方法。

E.IWindowSession#addToDisplay

IWindowSession是一个Binder对象,用于进行进程间通信,IWindowSession是Client端的代理,Server端的实现是Session。

F.Session#addToDisplay

之前的代码逻辑都是运行在本地进程中,而Session的addToDisplay()方法则运行在WMS所在的进程(即SystemServer进程)。

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

这就会调用到WMS中的addWindow()方法了。

G.WindowManagerService#addWindow

这个方法中的逻辑比较多,大概的实现逻辑我都在代码中注释了。

    public int addWindow(Session session, IWindow client, int seq,
            LayoutParams attrs, int viewVisibility, int displayId, Rect outFrame,
            Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
            DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,
            InsetsState outInsetsState) {
   
        int[] appOp = new int[1];
        // 检查权限
        int res = mPolicy.checkAddPermission(attrs, appOp);
        if (res != WindowManagerGlobal.ADD_OKAY) {
   
            return res;
        }

        boolean reportNewConfig = false;
        WindowState parentWindow = null;
        long origId;
        final int callingUid = Binder.getCallingUid();
        final int type = attrs.type;

        synchronized (mGlobalLock) {
   
            if (!mDisplayReady) {
   
                throw new IllegalStateException("Display has not been initialialized");
            }

            // 获取窗口要添加到哪个DisplayContent对象上
            final DisplayContent displayContent = getDisplayContentOrCreate(displayId, attrs.token);

            // 检查displayContent对象有效性
            if (displayContent == null) {
   
                Slog.w(TAG_WM, "Attempted to add window to a display that does not exist: "
                        + displayId + ".  Aborting.");
                return WindowManagerGlobal.ADD_INVALID_DISPLAY;
            }
            if (!displayContent.hasAccess(session.mUid)) {
   
                Slog.w(TAG_WM, "Attempted to add window to a display for which the application "
                        + "does not ha
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值