美文网首页Android启动性能Android专题系统知识
Android进阶(六):Activity启动时View显示过程

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

作者: Linhaojian | 来源:发表于2019-03-07 15:39 被阅读66次

    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_简书

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


    写技术文章初心

    • 技术知识积累
    • 技术知识巩固
    • 技术知识分享
    • 技术知识交流

    相关文章

      网友评论

        本文标题:Android进阶(六):Activity启动时View显示过程

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