Android绘制流程窗口启动流程分析(下)

原文转载:https://www.cnblogs.com/tiger-wang-ms/p/6517048.html

三、handleResumeActivity()流程

  在文章开头贴出的第一段AcitityThread.handleLauncherActivity()方法的代码中,执行完performLaunchAcitity()创建好Acitivity后,便会执行到handleResumeActivity()方法,该方法代码如下。
  

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
        ...// TODO Push resumeArgs into the activity for consideration
        // 该方法执行过程中会调用到Acitity的onResume()方法,返回的ActivityClientRecord对象描述的即是创建好的Activity     r = performResumeActivity(token, clearHide, reason);

        if (r != null) {
            final Activity a = r.activity;//返回之前创建的Acitivty

            if (localLOGV) Slog.v(
                TAG, "Resume " + r + " started activity: " +
                a.mStartedActivity + ", hideForNow: " + r.hideForNow
                + ", finished: " + a.mFinished);

            final int forwardBit = isForward ?
                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;

            // If the window hasn't yet been added to the window manager,
            // and this guy didn't finish itself or start another activity,
            // then go ahead and add the window.       // 判断该Acitivity是否可见,mStartedAcitity记录的是一个Activity是否还处于启动状态       // 如果还处于启动状态则mStartedAcitity为true,表示该activity还未启动好,则该Activity还不可见       boolean willBeVisible = !a.mStartedActivity;       // 如果启动的组建不是全屏的,mStartedActivity也会是true,此时依然需要willBeVisible为true以下的if逻辑就是针对这种情况的校正
            if (!willBeVisible) {
                try {
                    willBeVisible = ActivityManagerNative.getDefault().willActivityBeVisible(
                            a.getActivityToken());
                } catch (RemoteException e) {
                    throw e.rethrowFromSystemServer();
                }
            }
            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();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;          //PreserverWindow,一般指主题换了或者configuration变了情况下的Acitity快速重启机制
                if (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    // Normally the ViewRoot sets up callbacks with the Activity
                    // in addView->ViewRootImpl#setView. If we are instead reusing
                    // the decor view we have to notify the view root that the
                    // callbacks may have changed.
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                if (a.mVisibleFromClient && !a.mWindowAdded) {
                    a.mWindowAdded = true;            //调用了WindowManagerImpl的addView方法
                    wm.addView(decor, l);
                }

              ...
    }

  重点来看wm.addView()方法,该方法中的decor参数为Acitity对应的Window中的视图DecorView,wm为在创建PhoneWindow是创建的WindowManagerImpl对象,该对象的addView方法实际调用到到是单例对象WindowManagerGlobal的addView方法(前文有提到)。在看addView代码前,我先来看看WindowManagerGlobal对象成员变量。

private static WindowManagerGlobal sDefaultWindowManager;
    private static IWindowManager sWindowManagerService;
    private static IWindowSession sWindowSession;

    private final Object mLock = new Object();

    private final ArrayList mViews = new ArrayList();
    private final ArrayList mRoots = new ArrayList();
    private final ArrayList mParams =
            new ArrayList();
    private final ArraySet mDyingViews = new ArraySet();

三个成员变量mViews、mRoots和mParams分别是类型为View、ViewRootImpl和WindowManager.LayoutParams的数组。这里有这样的逻辑关系,每个View都对应着唯一的一个ViewRootImpl和WindowManager.LayoutRarams,即是1:1:1的关系。这三个数组长度始终保持一致,并且在同一个位置上存放的是互相关联的View、ViewRootImpl和WindowManager.LayoutParams对象。此外还有一个成员变量mDyView,保存的则是已经不需要但还未被系统会收到View。

  View与LayoutParams比较好理解,那ViewRootImpl对象的作用是什么呢?首先WindowManagerImpl是作为管理类,就像主管一样,根据Acitity和Window的调用请求,找到合适的做事的人;DecorView本身是FrameworkLayout,本事是一个View,所表示的是一种静态的结构;所以这里就需要一个真正做事的人,那就是ViewRootImpl类的工作。总结来讲ViewRootImpl的功能如下

  1. 完成了绘制过程。在ViewRootImpl类中,实现了perfromMeasure()、performDraw()、performLayout()等绘制相关的方法。
  2. 与系统服务进行交互,例如与AcitityManagerSerivice,DisplayService、AudioService等进行通信,保证了Acitity相关功能等正常运转。
  3. 触屏事件等分发逻辑的实现

  接下来我们进入WindowManagerGlobal.addView()方法的代码。
  

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ...

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {       ...            // If this is a panel window, then find the window it is being
            // attached to for future reference.       // 如果当前添加的是一个子视图,则还需要找他他的父视图       //这里我们分析的是添加DecorView的逻辑,没有父视图,故不会走到这里,panelParentView为null       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);
                    }
                }
            }            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);
       //保存互相对应的View、ViewRootImpl、WindowManager.LayoutParams到数组中
            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;
            }
        }
    }

 关注代码中加粗的两个方法,首先会创建一个ViewRootImpl对象,然后调用ViewRootImpl.setView方法,其中panelParentView在addView参数为DecorView是为null。进入ViewRootImpl.setView()代码。
 

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {          //初始化成员变量mView、mWindowAttraibutes          //mAttachInfo是View类的一个内部类AttachInfo类的对象                //该类的主要作用就是储存一组当View attach给它的父Window的时候Activity各种属性的信息                mView = view;
                mAttachInfo.mDisplayState = mDisplay.getState();
                mDisplayManager.registerDisplayListener(mDisplayListener, mHandler);

                mViewLayoutDirectionInitial = mView.getRawLayoutDirection();
                mFallbackEventHandler.setView(view);
                mWindowAttributes.copyFrom(attrs);
                ... //继续初始化一些变量,包含针对panelParentView不为null时的父窗口的一些处理
          mAdded = true;
                // 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.          // 这里调用异步刷新请求,最终会调用performTraversals方法来完成View的绘制          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();
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
                } 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();
                    }
                }

                ...
            }
        }
    }

相关变量初始化完成后,便会将mAdded设置为true,表示ViewRootImpl与setView传入的View参数已经做好了关联。之后便会调用requestLayout()方法来请求一次异步刷新,该方法后来又会调用到performTraversals()方法来完成view到绘制工作。注意到这里虽然完成了绘制的工作,但是我们创建Activity的源头是AMS中发起的,我们从一开始创建Acitivity到相对应的Window、DecorView这一大套对象时,还并未与AMS进程进行反馈。所以之后便会调用mWindowSession.addToDisplay()方法会执行IPC的跨进程通信,最终调用到AMS中的addWindow方法来在系统进程中执行相关加载Window的操作。

点击下方链接免费获取Android进阶资料:
https://shimo.im/docs/tXXKHgdjPYj6WT8d/

你可能感兴趣的:(android)