美文网首页
Android-Window、WindowManager和WMS

Android-Window、WindowManager和WMS

作者: 有腹肌的豌豆Z | 来源:发表于2020-09-27 15:12 被阅读0次

    1. Window体系

    Window体系说白了就是要在页面是显示的View,这个体系中包含多个类来共同完成view的显示其中包括Activity、Window、PhoneWindow、DecorView。

    Activity
    • 这个概念在我们一开始学Android的时候就理解为:一个Activity就是一个可视化的页面。
    • 因为它的setContentView()方法加载一个一个布局,这个布局也就跟我们看到的页面一样,所以可以说一个Activity就是一个页面。
    • 然后我们深入setContentView()方法查看发现是调用了getWindow的setContentView方法,我们再来说一下Window。
    Window
    • 查看Window源码发现Window是一个抽象类,他具体是实现类是PhoneWindow。
    • 所以上述 getWindow().setContentView(layoutResID);方法中getWindow返回的就是PhoneWindow,也就是调用了PhoneWindow的setContentView()方法。
    • Window用来控制视图,每一个视图都有一个Window,Activity,dialog,Toast都有一个对应的Window对象,没有Window的Activity就相当于Service
    • Window是抽象的概念,每一个Window都对应着一个View和ViewRootImpl,所以一般我们讨论的Window都是根View,比如Activity的根view,Window通过ViewRootImpl来和View建立联系
    • 每一个Window都需要指定一个Type,用于表示Window的种类,(应用Window,子Window和系统Window),Activity对应的窗口是应用窗口;PopupWindow,ContextMenu,OptionMenu是常用的子窗口;像Toast和系统警告提示框(如ANR)就是系窗口
    PhoneWindow
    • 每一个Activity都包含一个Window对象(dialog,toast 等也是新添加的window对象),而Window是一个抽象类,具体实现是PhoneWindow。在Activity中的setContentView实际上是调用PhoneWindow的setContentView方法。并且PhoneWindow中包含着成员变量DecorView。
    • 在PhoneWindow的构造方法中我们发现PhoneWindow获取了它的内部类DecorView。
    • 到这里我们就可以知道PhoneWindow调用setContentView()方法将布局文件渲染在mContentParent这个viewGroup上了。
    • return contentParent; 说白了mContentParent 其实就是 DecorView的 android:id="@android:id/content"。 就是那个FragmeLayout 容器。
    DecorView
    • 作为顶级View,DecorView一般情况下它内部会包含一个竖直方向的LinearLayout,上面的标题栏(titleBar),下面是内容栏。通常我们在Activity中通过setContentView所设置的布局文件就是被加载到id为android.R.id.content的内容栏里(FrameLayout)。
    • PhoneWindow的内部类,setContentView()方法最终完成的是将布局文件渲染到DecorView的content布局文件中

    WindowManager体系

    WindowManager体系的作用也就是管理Window最终管理的也就是渲染的View,主要有一下类或接口
    ViewManager、 WindowManager、WindowManagerImpl、WindowManagerGlobal、 ViewRootImpl、WindowManagerService

    ViewManager
    • ViewManager是一个接口,它内部只有三个方法。添加、修改、删除。
    public interface ViewManager{
        public void addView(View view, ViewGroup.LayoutParams params);
        public void updateViewLayout(View view, ViewGroup.LayoutParams params);
        public void removeView(View view);
    }
    
    WindowManager
    • 一个用来管理Window,添加,修改,删除的接口
    • 我们可以看到,WindowManager用来管理Window的接口都是针对它的根View进行操作的,说明根View才是Window存在的体现。
    • WindowManager也是一个接口它继承自ViewManager,它具体的实现是由WindowManagerImpl完成的。
    WindowManagerImpl
    • WindowManagerImpl继承自(实现)WindowManager,重写了ViewManager的增删改方法,但是具体是委托给WindowManagerGlobal完成的。
    WindowManagerGlobal
    • WindowManagerGlobal具体的增删改都是有它来完成的,以addView为例,将view,LayoutParams 作为参数传入到addView方法中。
    • 创建ViewRootImpl,并将view,ViewRootImpl,LayoutParams 添加到WindowManagerGlobal的List中。
    ViewRootImpl
    • 调用 root.setView(view, wparams, panelParentView); 这个方法主要做了两件事1、调用measure,layout,draw更新页面2、通知WindowManagerService进行Window的添加。

    WindowManagerImpl#addView()-->WindowManagerGlobal#addView()

    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        if (mView == null) {
            mView = view;
            ...
            //渲染UI
            requestLayout();
            ...
            try {
            ...
            //AIDL通知WindowManagerService
            res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                    getHostVisibility(), mDisplay.getDisplayId(),
                    mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                    mAttachInfo.mOutsets, mInputChannel);
            }
            mAttachInfo.mRootView = view;
        }
    }
    
    @Override
        public void requestLayout() {
            if (!mHandlingLayoutInLayoutRequest) {
                checkThread();
                mLayoutRequested = true;
                scheduleTraversals();
            }
        }
    
    void scheduleTraversals() {
            if (!mTraversalScheduled) {
                mTraversalScheduled = true;
                mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
                mChoreographer.postCallback(
                        Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
                if (!mUnbufferedInputDispatch) {
                    scheduleConsumeBatchedInput();
                }
                notifyRendererOfFramePending();
                pokeDrawLockIfNeeded();
            }
        }
    

    scheduleTraversals()中会通过handler去异步调用mTraversalRunnable接口。

    final class TraversalRunnable implements Runnable {
            @Override
            public void run() {
                doTraversal();
            }
        }
    

    也就是调用doTraversal方法

    void doTraversal() {
            if (mTraversalScheduled) {
                mTraversalScheduled = false;
                mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
    
                if (mProfile) {
                    Debug.startMethodTracing("ViewAncestor");
                }
    
                performTraversals();//最终会调用performTraversals
    
                if (mProfile) {
                    Debug.stopMethodTracing();
                    mProfile = false;
                }
            }
        }
    
    

    完成view的测量、布局、和 渲染

    private void performTraversals() {  
        ......  
        //测量View的宽高
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        ...
        //布置View的位置
        performLayout(lp, desiredWindowWidth, desiredWindowHeight);
        //监听事件
        if (triggerGlobalLayoutListener) {
            mAttachInfo.mRecomputeGlobalAttributes = false;
            //触发OnGlobalLayoutListener的onGlobalLayout()函数
            mAttachInfo.mTreeObserver.dispatchOnGlobalLayout();
        }
        ......  
        //渲染View
        performDraw();
        }
        ......  
    }
    
    WindowManagerService
    • 位于SystemServer进程的服务,用来管理窗口的创建、更新和删除,显示顺序等,是WindowManager这个管理接口的真正的实现类。

    调用逻辑

    1. 创建Activity、
      ActivityThread#handleLaunchActivity()#performLaunchActivity()
      在这里调用了创建的Activity的attach()方法。

    2.在Activity的attach()方法里面创建了 window 并且关联

    ....
    mWindow = new PhoneWindow(this, window, activityConfigCallback);
    ....
    mWindow.setWindowManager(
                 (WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
                    mToken, mComponent.flattenToString(),
                    (info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
            if (mParent != null) {
                mWindow.setContainer(mParent.getWindow());
            }
            mWindowManager = mWindow.getWindowManager();
    ....
    

    3.Activity.onCreate()

    public void setContentView(@LayoutRes int layoutResID) {
            getWindow().setContentView(layoutResID);
            initWindowDecorActionBar();
        }
    

    这里的getWindow()获取到的是PhoneWindow。

     @Override
        public void setContentView(int layoutResID) {
          
            if (mContentParent == null) {
                installDecor();
            } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                mContentParent.removeAllViews();
            }
    
            if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
                final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                        getContext());
                transitionTo(newScene);
            } else {
                mLayoutInflater.inflate(layoutResID, mContentParent);
            }
            mContentParent.requestApplyInsets();
            final Callback cb = getCallback();
            if (cb != null && !isDestroyed()) {
                cb.onContentChanged();
            }
            mContentParentExplicitlySet = true;
        }
    
    

    上面进过一系列的操作 ,到这里我们就可以知道PhoneWindow调用setContentView()方法将布局文件渲染在mContentParent这个viewGroup上了

    然后我们在找mContentParent是什么东西,源码第一句就判断mContentParent为空的估走了个installDecor()方法,我们判断这个方法因该是创建这个installDecor吧。

    private void installDecor() {
            mForceDecorInstall = false;
            if (mDecor == null) {
                mDecor = generateDecor(-1);
                mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mDecor.setIsRootNamespace(true);
                if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                    mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
                }
            } else {
                mDecor.setWindow(this);
            }
            if (mContentParent == null) {
                mContentParent = generateLayout(mDecor);
    
                 .....
    }
    

    可以看到installDecor方法再次判断mContentParent是否为空,然后调用了 mContentParent = generateLayout(mDecor);

    此方法不难看出,接收一个DecorView返回的这个名为mContentParent的ViewGroup ,ok继续

    protected ViewGroup generateLayout(DecorView decor) {
            // Apply data from current theme.
    
            TypedArray a = getWindowStyle();
    
            if (false) {
                System.out.println("From style:");
                String s = "Attrs:";
                for (int i = 0; i < R.styleable.Window.length; i++) {
                    s = s + " " + Integer.toHexString(R.styleable.Window[i]) + "="
                            + a.getString(i);
                }
                System.out.println(s);
            }
    
           .....
    
            mDecor.startChanging();
            mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
    
            ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);//ID_ANDROID_CONTENT = 
                                                                                //com.android.internal.R.id.content;
            if (contentParent == null) {
                throw new RuntimeException("Window couldn't find content container view");
            }
    
           ........
    
            return contentParent;
        }
    

    generateLayout() 这个方法源码贼多,但是我们大略可以猜到它是干嘛的,其实就是创建一个ViewGroup嘛,找return方法就完了。

    return contentParent; 说白了mContentParent 其实就是 DecorView的 android:id="@android:id/content"。

    这个时候mContentParent不等于空了,然后 mLayoutInflater.inflate(layoutResID, mContentParent); 也就把这个布局渲染给了 DecorView的 android:id="@android:id/content"

    返回DecorView

    protected DecorView generateDecor(int featureId) {
            // System process doesn't have application context and in that case we need to directly use
            // the context we have. Otherwise we want the application context, so we don't cling to the
            // activity.
            Context context;
            if (mUseDecorContext) {
                Context applicationContext = getContext().getApplicationContext();
                if (applicationContext == null) {
                    context = getContext();
                } else {
                    context = new DecorContext(applicationContext, getContext());
                    if (mTheme != -1) {
                        context.setTheme(mTheme);
                    }
                }
            } else {
                context = getContext();
            }
            return new DecorView(context, featureId, this, getAttributes());
        }
    

    到这里 XML的数据已经传进来了 ,注意这个时候Activity的生命周期是onCreate(),我们的布局还没有显示出来的。继续跟...

    4.DecorView和WindowManager是如何关联起来的
    ActivityThread#handleResumeActivity()

    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,String reason) {
           
        ...
           
        final Activity a = r.activity;
    
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager();
            ...
    
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                } else {
                    a.onWindowAttributesChanged(l);
                }
            }
           ....
    }
    

    看上面可以知道 这个时候 将windowmanager和decorview 关联到一起了。

    1. wm.addView()里面的操作

    WindowManagerInpl#addView() 这个里面的view就是decorview
    WindowManagerInpl是WindowManager的实现类。

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

    WindowManagerGlobal#addView() 这个里面的view就是decorview

    public void addView(View view, ViewGroup.LayoutParams params, Display display, Window parentWindow) {
           
           ...
    
            ViewRootImpl root;
            View panelParentView = null;
    
            synchronized (mLock) {
                
                ...
    
                root = new ViewRootImpl(view.getContext(), display);
    
                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 {
                    root.setView(view, wparams, panelParentView);
                } catch (RuntimeException e) {
                    // BadTokenException or InvalidDisplayException, clean up.
                    if (index >= 0) {
                        removeViewLocked(index, true);
                    }
                    throw e;
                }
            }
        }
    

    到这里 setContentView(xml) --> decorview --> 与viewrootimpl 关联到一起了。

    其实打开一个 Activity,当它的 onCreate---onResume 生命周期都走完后,才将它的 DecoView 与新建的一个 ViewRootImpl 对象绑定起来,同时开始安排一次遍历 View 任务也就是绘制 View 树的操作等待执行,然后将 DecoView 的 parent 设置成 ViewRootImpl 对象。

    这也就是为什么在 onCreate---onResume 里获取不到 View 宽高的原因,因为在这个时刻 ViewRootImpl 甚至都还没创建,更不用说是否已经执行过测量操作了。

    还可以得到一点信息是,一个 Activity 界面的绘制,其实是在 onResume() 之后才开始的。

    后面的待续 。。。

    相关文章

      网友评论

          本文标题:Android-Window、WindowManager和WMS

          本文链接:https://www.haomeiwen.com/subject/fdkfuktx.html