从 Activity 被实例化的那一刻起,到最终屏幕上亮起绚丽的像素,系统底层到底经历了怎样严密而精妙的物理流转?
这是一张 Android UI 渲染管线的微观物理蓝图,它完美展现了控制面(Control Plane)、数据面(Data Plane)与状态机(State Machine) 之间的极致协奏。
1. 触发启动 (Triggering the Launch)
AMS(ActivityManagerService)向 App 进程发送 Binder 事务,调用 ApplicationThread.scheduleLaunchActivity,传入 ActivityClientRecord(一个包含目标 Activity 类名,如 com.example.MainActivity 的数据包)。
2. 线程交接 (Thread Handoff)
App 的 Binder 线程收到消息后,立刻通过 Handler 将其抛给主线程。
3. 反射创建 (Reflection & Creation)
ActivityThread 通过反射实例化该 Activity。
4. 状态维护 (Activity Management)
ActivityThread 内部维护着一个 Map(具体为 mActivities),用于跟踪当前进程内所有存活的 Activity 实例。
5. 绑定窗口 (Window Binding)
调用 Activity.attach(),在其中创建 PhoneWindow,并与 Activity 紧密绑定。
6. 构建视图树 (Building the View Tree)
在 onCreate 中调用 setContentView。Activity 委托给 PhoneWindow 创建 DecorView。随后,LayoutInflater 解析 R.layout.xxx 为 View 树,并挂载到 DecorView 内部的 android.R.id.content(一个 FrameLayout)中。
7. 准备画布与触发重绘 (Preparing the Canvas & The Trigger Mechanism)
onResume 执行后,调用 WindowManager.addView(mDecorView)。内部会交由进程单例 WindowManagerGlobal 处理。它创建 ViewRootImpl,并强引用将其存入内部的 mRoots 列表中,以管理窗口的生命周期。ViewRootImpl 包含两个核心成员:指向 DecorView 的 mView,以及指向 WMS 的 Binder 代理 mWindowSession。
注意:当 View 需要触发重绘(调用 View.invalidate())时,它并不会直接跨进程去通知 WMS。在视图树挂载阶段(dispatchAttachedToWindow),ViewRootImpl 会创建一个 View.AttachInfo 对象(内部持有 ViewRootImpl 的强引用),并逐层注入给 View 树中的每一个 View。当 invalidate()被调用时,View 会取出自身的 mAttachInfo,反向调用 mAttachInfo.mViewRootImpl.invalidateChild(),将请求一路冒泡回根节点。
8. 分配物理画布 (Canvas Allocation)
ViewRootImpl.setView() 被调用。它通过 mWindowSession.addToDisplay() 跨进程向 WMS 发起同步请求。WMS 协调 SurfaceFlinger 创建 Layer 和 BufferQueue,并返回 SurfaceControl 句柄。ViewRootImpl 借此创建 Surface 并获取队列的生产端句柄。
9. 调度重绘 (Scheduling the Draw)
ViewRootImpl 调用 requestLayout(),向主线程的 MessageQueue 插入同步屏障(Sync Barrier) ,并向 Choreographer 投递一个 CALLBACK_TRAVERSAL 回调。
10. VSYNC 唤醒 (VSYNC & Wakeup)
当硬件 VSYNC 信号到来时,Choreographer 发送异步消息。主线程 Looper 突破同步屏障取走消息,执行 ViewRootImpl.performTraversals()。
11. 测量、布局与录制 (Measure, Layout, Draw)
- Measure:从
DecorView开始递归,计算每个 View 所需尺寸。 - Layout:将算好尺寸的 View 摆放到
Surface对应的相对坐标上。 - Draw:开启硬件加速时,Draw 并不直接画像素,而是将所有绘制动作录制成一棵
DisplayList指令树。
12. 线程卸载 (Thread Offloading)
主线程通过 SyncQueue 将 DisplayList 同步给 RenderThread。交接完毕后,主线程立刻回去处理下一个用户点击事件。主线程绝不在这里死等 GPU。
13. GPU 翻译 (GPU Translation)
RenderThread 将 DisplayList 翻译成底层的 OpenGL / Vulkan 渲染指令。
14. 异步渲染 (Asynchronous Rendering)
RenderThread 从 Surface 队列申请一块 GraphicBuffer,将指令提交给 GPU 后,立即将其重新入队(标记为 QUEUED),并附带一个处于锁定(未解锁)状态的 Fence。
15. 合成上屏 (Composition & Display)
下一个 VSYNC 到来时,SurfaceFlinger 遍历队列并检查 Fence 信号(确保 GPU 渲染完成)。一旦解锁,便取走 Buffer(标记为 ACQUIRED),刷新图层属性,交由硬件合成器(HWC)完成最终的屏幕渲染。
💡 架构师总结 (Architect's Takeaway)
这个 15 步的流程,完美彰显了 Android 架构的优雅之处:控制面与数据面分离、异步渲染,以及基于 Fence 驱动的状态机。 通过将 GPU 渲染工作卸载给 RenderThread,并利用多缓冲队列(Multi-buffered queue),Android 成功消除了主线程阻塞,实现了零拷贝且无画面撕裂的丝滑渲染。
(注:关于第 13-15 步更深度的物理机制——包括 GraphicBuffer 的四大状态生命周期 [FREE -> DEQUEUED -> QUEUED -> ACQUIRED] 以及 Gralloc 的作用,请参阅我的上一篇文章: juejin.cn/post/770153…)
English Version
Under the Hood: The 15-Step Journey of an App's first Android UI Frame
What truly happens from the moment an Activity is instantiated to the exact moment pixels light up the screen?
Here is the microscopic physical blueprint of the Android UI Rendering Pipeline, breaking down the perfect choreography of the Control Plane, Data Plane, and State Machine.
1. Triggering the Launch
AMS (ActivityManagerService) sends a Binder transaction to the App process, invoking ApplicationThread.scheduleLaunchActivity with the ActivityClientRecord (a data package containing the target Activity's class name, e.g., com.example.MainActivity).
2. Thread Handoff
The App's Binder thread receives the message and immediately posts it via a Handler to the main thread.
3. Reflection & Creation
ActivityThread instantiates the Activity via Reflection.
4. Activity Management
ActivityThread maintains a Map (specifically mActivities) to track all live Activity instances within the current process.
5. Window Binding
Activity.attach() is invoked, inside which a PhoneWindow is created and tightly bound to the Activity.
6. Building the View Tree
During onCreate, setContentView is called. The Activity delegates to PhoneWindow, which creates the DecorView. LayoutInflater then parses R.layout.xxx into a View tree and mounts it into android.R.id.content (the FrameLayout inside DecorView).
7. Preparing the Canvas & The Trigger Mechanism
After onResume, WindowManager.addView(mDecorView) is called. Internally, this request is delegated to WindowManagerGlobal, a process-wide singleton. It creates the ViewRootImpl and strongly references it in its internal mRoots list to manage the window's lifecycle. ViewRootImplcontains two core members: mView (pointing to DecorView) and mWindowSession (the Binder proxy to WMS).
Note here, when a View needs to trigger a redraw via View.invalidate(), it does not communicate with WMS directly. During the view tree attachment phase (dispatchAttachedToWindow), ViewRootImpl creates a View.AttachInfo object (which holds a strong reference to the ViewRootImpl) and injects it into every View in the hierarchy. When invalidate() is called, the View retrieves its mAttachInfo and invokes mAttachInfo.mViewRootImpl.invalidateChild(), bubbling the request back to the root.
8. Canvas Allocation
ViewRootImpl.setView() is called. It makes a synchronous cross-process request to WMS via mWindowSession.addToDisplay(). WMS coordinates with SurfaceFlinger to create a Layer and a BufferQueue, returning a SurfaceControl handle. ViewRootImpl uses this to create the Surfaceand acquires the Producer handle of the BufferQueue.
9. Scheduling the Draw
ViewRootImpl calls requestLayout(), inserting a Sync Barrier into the main thread's MessageQueue, and posts a CALLBACK_TRAVERSAL to the Choreographer.
10. VSYNC & Wakeup
When the hardware VSYNC signal arrives, Choreographer posts an asynchronous message. The Looper bypasses the Sync Barrier, takes the message, and executes ViewRootImpl.performTraversals().
11. Measure, Layout, Draw
- Measure: Recursively calculates the required size of each View from
DecorViewdownwards. - Layout: Positions the sized Views at specified coordinates relative to the
Surface. - Draw: With hardware acceleration enabled, it doesn't draw pixels directly. Instead, it records all draw commands into a
DisplayListinstruction tree.
12. Thread Offloading
The main thread syncs the DisplayList to the RenderThread via SyncQueue. The handoff is complete, and the main thread immediately resumes processing the next user input event. It never waits for the GPU.
13. GPU Translation
RenderThread translates the DisplayList into low-level OpenGL / Vulkan commands.
14. Asynchronous Rendering
RenderThread requests a GraphicBuffer from the Surface queue, submits the commands to the GPU, and immediately enqueues the GraphicBuffer back to the queue (marking it as QUEUED) with a locked Fence.
15. Composition & Display
When the next VSYNC arrives, SurfaceFlinger traverses the queues and checks the Fence signal(ensuring the GPU has finished rendering). Once unlocked, it acquires the buffer (marking it ACQUIRED), updates the Layers, and passes them to the HWC (Hardware Composer) for final rendering and display.
This 15-step flow highlights the elegance of Android's architecture: Control/Data Plane separation, asynchronous rendering, and Fence-driven state machines. By offloading GPU rendering to the RenderThread and leveraging a multi-buffered queue, Android eliminates main-thread blocking and achieves zero-copy, tear-free rendering.
(Note: For a deeper dive into the physical mechanics of Steps 13-15—including the four-state lifecycle of a GraphicBuffer [FREE -> DEQUEUED -> QUEUED -> ACQUIRED] and the role of Gralloc—please refer to my previous article here: juejin.cn/post/770153…)