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<View> mViews = new ArrayList<View>();

    private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();

    private final ArrayList<WindowManager.LayoutParams> mParams =

            new ArrayList<WindowManager.LayoutParams>();

    private final ArraySet<View> mDyingViews = new ArraySet<View>();


三个成员变量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的操作。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355