Android进阶(六):Activity启动时View显示过程(浅析)

1.前言

  • 最近一直在看 《Android进阶解密》 的一本书,这本书编写逻辑、流程都非常好,而且很容易看懂,非常推荐大家去看看(没有收广告费,单纯觉得作者写的很好)。
  • 上一篇简单的介绍了Android进阶(五):Service启动过程(最详细&最简单)
  • 今天就介绍:Activity启动时View显示过程 (基于Android 8.0 系统)。
  • 文章中实例 linhaojian的Github

2.View显示过程时序总图

  • 引用下面的时序总图,方便更容易理解下文源码部分的内容。


    Activity启动时View的显示流程.png

3.源码分析

3.1 ActivityThread

    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        // Activity调用完onResume之后,会真正开始绘制界面
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();//PhoneWindow
            View decor = r.window.getDecorView();// 1   
            decor.setVisibility(View.INVISIBLE);
            //Activity中的WindowMangerImp对象,它实现ViewManager接口
            ViewManager wm = a.getWindowManager();//2  
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;//把phoneWindow里的DecorView赋值给Activity的decor
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            if (r.mPreserveWindow) {
                a.mWindowAdded = true;
                r.mPreserveWindow = false;
                ViewRootImpl impl = decor.getViewRootImpl();
                if (impl != null) {
                    impl.notifyChildRebuilt();
                }
            }
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    //将decor添加在WindowManager(WindowMangerImp)中
                    wm.addView(decor, l);//3  
                } else {
                    // The activity will get a callback for this {@link LayoutParams} change
                    // earlier. However, at that time the decor will not be set (this is set
                    // in this method), so no action will be taken. This call ensures the
                    // callback occurs with the decor set.
                    a.onWindowAttributesChanged(l);
                }
            }
    }
  • 注释1:获取PhoneWindow中的DecorView,DecorView在Activity调用setContentView时被创建
  • 注释2:获取ViewManager的实现类WindowMangaerImp,WindowManagerImp在Activity中attach()被创建
  • 注释3:将DecorView与相关的布局参数传递至WindowManagerImp中

3.2 WindowManagerImpl

public final class WindowManagerImpl implements WindowManager {
    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);// 1
    }
}
  • 注释1:其实就是运用了外观模式,真正的实现在WindowManagerGloball的addView()

3.3 WindowManagerGlobal

public final class WindowManagerGlobal {
    public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
            //...
            root = new ViewRootImpl(view.getContext(), display);// 1
            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);// 2
            } catch (RuntimeException e) {
                // BadTokenException or InvalidDisplayException, clean up.
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
                throw e;
            }
    }
}
  • 注释1:创建ViewRootImpl实例
  • 注释2:把decorview传递至ViewRootImpl

3.4 ViewRootImpl

public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
    public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
                // 先把UI界面的数据准备好(测量--布局--绘制)
                requestLayout();// 1
                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();
                    //将该Window添加到屏幕。
                    //mWindowSession实现了IWindowSession接口,它是Session的客户端Binderd代理对象.
                    //addToDisplay是一次AIDL的跨进程通信,通知WindowManagerService添加IWindow
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(), mWinFrame,
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel);// 2
                } catch (RemoteException e) {
                    //...
                } finally {
                    if (restore) {
                        attrs.restore();
                    }
                }
    }
}
  • 注释1:刷新界面,下文会继续介绍
  • 注释2:**mWindowSession是Session的代理对象,而Session在WindowManagerService中被初始化,这里通过AIDL的方式与WindowManagerService进行跨进程通讯。
    **;

3.5 Session

class Session extends IWindowSession.Stub implements IBinder.DeathRecipient {
    @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) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId, outFrame,
                outContentInsets, outStableInsets, outOutsets, outDisplayCutout, outInputChannel);// 1
    }
}
  • 注释1:其实就是调用WindowManagerService的addWindow()

3.6 WindowManagerService

public class WindowManagerService extends IWindowManager.Stub
        implements Watchdog.Monitor, WindowManagerPolicy.WindowManagerFuncs {
    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) {
            //...
            final WindowState win = new WindowState(this, session, client, token, parentWindow,
                    appOp[0], seq, attrs, viewVisibility, session.mUid,
                    session.mCanAddInternalSystemWindow);// 1
             // ...
            // 初始化SurfaceSession对象同时会调用底层相关内容(SurfaceComposerClient,SurfaceComposerClient
            // 是与SurfaceFlinger通讯的代理对象)
            win.attach();// 2
            mWindowMap.put(client.asBinder(), win);
            // ....
     }
}
  • 注释1:创建表示窗口状态的对象,并把相关信息传入
  • 注释2:调用窗口状态对象的初始化函数

3.7 WindowState

class WindowState extends WindowContainer<WindowState> implements WindowManagerPolicy.WindowState {
    void attach() {
        if (localLOGV) Slog.v(TAG, "Attaching " + this + " token=" + mToken);
        mSession.windowAddedLocked(mAttrs.packageName);//1
    }
}
  • 注释1:调用Session的windowAddedLocked函数
  • Session的windowAddedLocked()
    void windowAddedLocked(String packageName) {
        mPackageName = packageName;
        mRelayoutTag = "relayoutWindow: " + mPackageName;
        if (mSurfaceSession == null) {
            if (WindowManagerService.localLOGV) Slog.v(
                TAG_WM, "First window added to " + this + ", creating SurfaceSession");
            mSurfaceSession = new SurfaceSession();// 1
            if (SHOW_TRANSACTIONS) Slog.i(
                    TAG_WM, "  NEW SURFACE SESSION " + mSurfaceSession);
            mService.mSessions.add(this);
            if (mLastReportedAnimatorScale != mService.getCurrentAnimatorScale()) {
                mService.dispatchNewAnimatorScaleLocked(this);
            }
        }
        mNumWindow++;
    }
  • 注释1:其实就是初始化SurfaceSession,SurfaceSession类中大部分都是native的函数,该类的作用主要是初始化底层库中的SurfaceComposerClient(与SurfaceFlinger通讯,SurfaceFlinger才是真正实现合成界面并显示至手机屏幕中)
  • 到这里,我们大概知道ActivityThread.handleResumeActivity()所引发的一些操作:
    • 1.ActivityThread 通过 WindowManagerGlobal 创建ViewRootImpl(一个Winodw可包含多个ViewRootImpl);
    • 2.ViewRootImpl 通过IWindowSession代理对象最终与WindowManagerService通讯;
    • 3.WindowManagerService中会为应用程序创建一个WindowState,代表着应用程序窗口信息;
    • 4.WindowState中通过Session创建一个SurfaceSession(SurfaceSession作用:就是使应用程序与Surfacelginer构建通讯环境);
      ViewRootImpl关联SurfaceLinger.png
  • 下面就开始真正的把绘制内容填充至手机屏幕(SurfaceWindowUI载体,所以绘制的内容最终在应用程序端会变成Surface);

3.8 ViewRootImpl的requestLayout()

    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            //启动一个延迟任务,任务内容:mTraversalRunnable
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }
    final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }
            performTraversals();// 1
            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }
  • 注释1:performTraversals真正的界面绘制过程
    private void performTraversals() {
        //...
       relayoutResult = relayoutWindow(params, viewVisibility, insetsPending);// 1
        //...
        performMeasure(); 
        //...
        performLayout(lp, mWidth, mHeight); 
        //...
        performDraw();
    }
  • performTraversals函数中,包含4个比较重要的方法,如上述代码块中的注释1-4
  • 注释1:relayoutWindow函数会继续跟WindowManagerService通讯,下文会展开他们通讯的作用
    private int relayoutWindow(WindowManager.LayoutParams params, int viewVisibility,
            boolean insetsPending) throws RemoteException {
               //通过Session的代理对象,调用其中的relayout函数,而relayout最终也是调用WindowManangerService的relayoutWindow函数
                int relayoutResult = mWindowSession.relayout(mWindow, mSeq, params,
                (int) (mView.getMeasuredWidth() * appScale + 0.5f),
                (int) (mView.getMeasuredHeight() * appScale + 0.5f), viewVisibility,
                insetsPending ? WindowManagerGlobal.RELAYOUT_INSETS_PENDING : 0, frameNumber,
                mWinFrame, mPendingOverscanInsets, mPendingContentInsets, mPendingVisibleInsets,
                mPendingStableInsets, mPendingOutsets, mPendingBackDropFrame, mPendingDisplayCutout,
                mPendingMergedConfiguration, mSurface);// 1
          //....
        return relayoutResult;
    }
  • 注释1:通过Session的代理对象,最终与WindowManangerService通讯,从传入的参数观看到一个mSurface,而这个就是显示界面到屏幕的关键,那这个mSurface从哪里创建呢?它里面包含什么内容?;
  • Surface创建
public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
    // These can be accessed by any thread, must be protected with a lock.
    // Surface can never be reassigned or cleared (use Surface.clear()).
    public final Surface mSurface = new Surface();
}
  • 从上述代码可以发现,其实在ViewRootImpl创建的同时初始化了一个空壳的Surface,上述的relayoutWindow函数把这个空壳Surface传递至WindowManangerService具体是干什么,我们进行跟踪。
  • WindowManangerService的relayoutWindow函数
    public int relayoutWindow(Session session, IWindow client, int seq, LayoutParams attrs,
            int requestedWidth, int requestedHeight, int viewVisibility, int flags,
            long frameNumber, Rect outFrame, Rect outOverscanInsets, Rect outContentInsets,
            Rect outVisibleInsets, Rect outStableInsets, Rect outOutsets, Rect outBackdropFrame,
            DisplayCutout.ParcelableWrapper outCutout, MergedConfiguration mergedConfiguration,
            Surface outSurface) {
            //...
            try {
                    result = createSurfaceControl(outSurface, result, win, winAnimator);
                } catch (Exception e) {
                    mInputMonitor.updateInputWindowsLw(true /*force*/);
                    Slog.w(TAG_WM, "Exception thrown when creating surface for client "
                             + client + " (" + win.mAttrs.getTitle() + ")",
                             e);
                    Binder.restoreCallingIdentity(origId);
                    return 0;
                }
             //...
    }
    //.....
    private int createSurfaceControl(Surface outSurface, int result, WindowState win,
            WindowStateAnimator winAnimator) {
        if (!win.mHasSurface) {
            result |= RELAYOUT_RES_SURFACE_CHANGED;
        }
        WindowSurfaceController surfaceController;
        try {
            Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "createSurfaceControl");
            surfaceController = winAnimator.createSurfaceLocked(win.mAttrs.type, win.mOwnerUid);// 1
        } finally {
            Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
        }
        if (surfaceController != null) {
            surfaceController.getSurface(outSurface); // 2
            if (SHOW_TRANSACTIONS) Slog.i(TAG_WM, "  OUT SURFACE " + outSurface + ": copied");
        } else {
            // For some reason there isn't a surface.  Clear the
            // caller's object so they see the same state.
            Slog.w(TAG_WM, "Failed to create surface control for " + win);
            outSurface.release();
        }
        return result;
    } 
  • 注释1:winAnimator.createSurfaceLocked实际上是创建了一个SurfaceControl(SurfaceControl负责操作与维护Surface)
  • 注释2:就是把SurfaceControl关联至outSurface中
  • 到这里,我们大概知道ViewRootImpl.relayoutWindow所触发的操作:
    • 1.ViewRootImplSurface通过Session的代理对象,最终传递至WindowManangerService
    • 2.WindowManangerService中通过创建WindowSurfaceController
    • 3.WindowSurfaceController中实现Surface关联SurfaceControl
    • 4.SurfaceControl会创建Native层的Surface,并把指针赋值与ViewRootImpl的Surface;
      Surface关联SurfaceControl.png
  • 下面继续跟踪View是如何与Surface产生关联;

3.8 ViewRootImpl的performDraw()

    private void performDraw() {
        try {
            // 调用draw绘制界面,最终会调用drawSoftware()
            boolean canUseAsync = draw(fullRedrawNeeded);
            if (usingAsyncReport && !canUseAsync) {
                mAttachInfo.mThreadedRenderer.setFrameCompleteCallback(null);
                usingAsyncReport = false;
            }
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
   }
    private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty, Rect surfaceInsets) {
         //.....
         final Canvas canvas;
         //.....
         canvas = mSurface.lockCanvas(dirty);// 1
         //.....
         mView.draw(canvas);// 2
         //.....
         surface.unlockCanvasAndPost(canvas); // 3
    }
  • 注释1:通过Surface获取Canvas画布
  • 注释2:将画布传入至DecorView的draw方法中,并向画布绘制或者填充内容
  • 注释3:把绘制完的画布传递至Surface,最后Surface会调用相关的native方法,把界面数据添加至底层Buffer中,待SurfaceFlinger处理绘制
    Surface填充内容流程.png

4.关系链

View显示过程关系链.png
  • 综合源码分析与上述图示,可汇总以下信息:
    1.ViewRootImpl通过创建对应的SessionSurfaceSession,并与SurfaceFlinger构建通讯环境;
    2.WindowManangerService创建SurfaceController管理窗口属性与创建Native层的Surface,并将Native的Surface指向ViewRootImplSurface;
    3.ViewRootImpl中会把View的内容传递至Surface中,最后会把界面数据保存至ShareBuffer
    4.SurfaceFlinger接收到ShareBuffer后,通知相关硬件进行显示;

5.总结

  • 到此,Activity启动时View显示过程介绍完毕。
  • 如果喜欢我的分享,可以点击 关注 或者 ,你们支持是我分享的最大动力 。
  • linhaojian的Github

欢迎关注linhaojian_CSDN博客或者linhaojian_简书

不定期分享关于安卓开发的干货。


写技术文章初心

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

推荐阅读更多精彩内容