Android-Window、WindowManager和WMS

2020-09-27  本文已影响0人  有腹肌的豌豆Z

1. Window体系

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

Activity
Window
PhoneWindow
DecorView

WindowManager体系

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

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
WindowManagerImpl
WindowManagerGlobal
ViewRootImpl

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

调用逻辑

  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() 之后才开始的。

后面的待续 。。。

上一篇下一篇

猜你喜欢

热点阅读