分析Android Choreographer源碼
一、前言
目前大部分手機都是 60Hz 的刷新率,也就是 16.6ms 刷新一次,系統(tǒng)為了配合屏幕的刷新頻率,將 Vsync 的周期也設(shè)置為 16.6 ms,每個 16.6 ms , Vsync 信號喚醒 Choreographer 來做 App 的繪制操作,這就是引入 Choreographer 的主要作用。了解 Choreographer 還可以幫助 App 開發(fā)者知道程序每一幀運行的基本原理,也可以加深對 Message、Handler、Looper、MessageQueue、Measure、Layout、Draw 的理解
二、主線程運行機制的本質(zhì)
在介紹 Choreographer 之前,我們先理一下 Android 主線程運行的本質(zhì),其實就是 Message 的處理過程,我們的各種操作,包括每一幀的渲染,手勢操作 ,都是通過 Message 的形式發(fā)給主線程的 MessageQueue ,MessageQueue 處理完消息繼續(xù)等下一個消息,如下圖所示
MethodTrace 圖示
Systrace 圖示
可以發(fā)現(xiàn),每一幀時間都是固定的。所以一旦一個Message 的處理時間超過了 16.6ms 就會引起卡頓。
三、Choreographer 簡介
Choreographer 扮演 Android 渲染鏈路中承上啟下的角色
1.承上:負責(zé)接收和處理 App 的各種更新消息和回調(diào),等到 Vsync 到來的時候統(tǒng)一處理。比如集中處理 Input(主要是 Input 事件的處理) 、Animation(動畫相關(guān))、Traversal(包括 measure、layout、draw 等操作) ,判斷卡頓掉幀情況,記錄 CallBack 耗時等
2.啟下:負責(zé)請求和接收 Vsync 信號。接收 Vsync 事件回調(diào)(通過 FrameDisplayEventReceiver.onVsync );請求 Vsync(FrameDisplayEventReceiver.scheduleVsync) .
從上面可以看出來, Choreographer 擔(dān)任的是一個工具人的角色,他之所以重要,是因為通過Choreographer + SurfaceFlinger + Vsync + TripleBuffer這一套從上到下的機制,保證了 Android App 可以以一個穩(wěn)定的幀率運行(目前大部分是 60fps),減少幀率波動帶來的不適感。
3.1、Choreographer 的工作流程
Choreographer 初始化SurfaceFlinger 的 appEventThread 喚醒發(fā)送 Vsync ,Choreographer 回調(diào) FrameDisplayEventReceiver.onVsync , 進入 Choreographer 的主處理函數(shù) doFrame
- 初始化 FrameHandler ,綁定 Looper
- 初始化 FrameDisplayEventReceiver ,與 SurfaceFlinger 建立通信用于接收和請求 Vsync
- 初始化 CallBackQueues
Choreographer.doFrame 計算掉幀邏輯
Choreographer.doFrame 處理 Choreographer 的第一個 callback : input
Choreographer.doFrame 處理 Choreographer 的第二個 callback : animation
Choreographer.doFrame 處理 Choreographer 的第三個 callback : insets animation
Choreographer.doFrame 處理 Choreographer 的第四個 callback : traversalChoreographer.doFrame 處理 Choreographer 的第五個 callback : commit ?traversal-draw 中 UIThread 與 RenderThread 同步數(shù)據(jù)
RenderThread 處理繪制數(shù)據(jù),真正進行渲染
將渲染好的 Buffer swap 給 SurfaceFlinger 進行合成
四、Choreographer 源碼分析
4.1、Choreographer 的單例初始化
// Thread local storage for the choreographer. private static final ThreadLocal<Choreographer> sThreadInstance = new ThreadLocal<Choreographer>() { @Override protected Choreographer initialValue() { Looper looper = Looper.myLooper(); if (looper == null) { throw new IllegalStateException("The current thread must have a looper!"); } Choreographer choreographer = new Choreographer(looper, VSYNC_SOURCE_APP); if (looper == Looper.getMainLooper()) { mMainInstance = choreographer; } return choreographer; } };
這里采用的是ThreadLocal 來構(gòu)造單例,這樣每個線程都會有一個屬于自己的 choreographer 實例。
接下去看choreographer 的構(gòu)造函數(shù)
private Choreographer(Looper looper, int vsyncSource) { mLooper = looper; mHandler = new FrameHandler(looper); // 這里可以發(fā)現(xiàn)只有在為 true 的時候才會使用 vsync mDisplayEventReceiver = USE_VSYNC ? new FrameDisplayEventReceiver(looper, vsyncSource) : null; mLastFrameTimeNanos = Long.MIN_VALUE; // 每一幀的間隔是根據(jù)刷新頻率來的 mFrameIntervalNanos = (long)(1000000000 / getRefreshRate()); mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1]; // 給每一種回調(diào)類型都創(chuàng)建了一個隊列 for (int i = 0; i <= CALLBACK_LAST; i++) { mCallbackQueues[i] = new CallbackQueue(); } // b/68769804: For low FPS experiments. setFPSDivisor(SystemProperties.getInt(ThreadedRenderer.DEBUG_FPS_DIVISOR, 1)); }
這里做了幾個初始化操作,根據(jù)Looper對象生成,Looper和線程是一對一的關(guān)系,對應(yīng)上面說明里的每個線程對應(yīng)一個Choreographer。
- 初始化FrameHandler。接收處理消息。
- 初始化FrameDisplayEventReceiver。FrameDisplayEventReceiver用來接收垂直同步脈沖,就是VSync信號,VSync信號是一個時間脈沖,一般為60HZ,用來控制系統(tǒng)同步操作,怎么同ChoreoGrapher一起工作的,將在下文介紹。
- 初始化mLastFrameTimeNanos(標(biāo)記上一個frame的渲染時間)以及mFrameIntervalNanos(幀率,fps,一般手機上為1s/60)。
- 初始化CallbackQueue,callback隊列,將在下一幀開始渲染時回調(diào)。
接下去看看 FrameHandler 和 FrameDisplayEventReceiver 的結(jié)構(gòu)。
private final class FrameHandler extends Handler { public FrameHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DO_FRAME: doFrame(System.nanoTime(), 0); break; case MSG_DO_SCHEDULE_VSYNC: doScheduleVsync(); break; case MSG_DO_SCHEDULE_CALLBACK: doScheduleCallback(msg.arg1); break; } } }
看上面的代碼,就是一個簡單的Handler。處理3個類型的消息。
- MSG_DO_FRAME:開始渲染下一幀的操作
- MSG_DO_SCHEDULE_VSYNC:請求 Vsync 信號
- MSG_DO_SCHEDULE_CALLBACK:請求執(zhí)行 callback
下面再細分一下,分別詳細看一下這三個步驟是怎么實現(xiàn)的。
4.2、FrameDisplayEventReceiver
private final class FrameDisplayEventReceiver extends DisplayEventReceiver implements Runnable { private boolean mHavePendingVsync; private long mTimestampNanos; private int mFrame; public FrameDisplayEventReceiver(Looper looper, int vsyncSource) { super(looper, vsyncSource); } // TODO(b/116025192): physicalDisplayId is ignored because SF only emits VSYNC events for // the internal display and DisplayEventReceiver#scheduleVsync only allows requesting VSYNC // for the internal display implicitly. @Override public void onVsync(long timestampNanos, long physicalDisplayId, int frame) { // Post the vsync event to the Handler. // The idea is to prevent incoming vsync events from completely starving // the message queue. If there are no messages in the queue with timestamps // earlier than the frame time, then the vsync event will be processed immediately. // Otherwise, messages that predate the vsync event will be handled first. long now = System.nanoTime(); if (timestampNanos > now) { Log.w(TAG, "Frame time is " + ((timestampNanos - now) * 0.000001f) + " ms in the future! Check that graphics HAL is generating vsync " + "timestamps using the correct timebase."); timestampNanos = now; } if (mHavePendingVsync) { Log.w(TAG, "Already have a pending vsync event. There should only be " + "one at a time."); } else { mHavePendingVsync = true; } mTimestampNanos = timestampNanos; mFrame = frame; Message msg = Message.obtain(mHandler, this); msg.setAsynchronous(true); mHandler.sendMessageAtTime(msg, timestampNanos / TimeUtils.NANOS_PER_MS); } @Override public void run() { mHavePendingVsync = false; doFrame(mTimestampNanos, mFrame); } }
FrameDisplayEventReceiver 繼承自 DisplayEventReceiver,同時也實現(xiàn)了Runnable 接口,是處于 Choreographer 中的私有內(nèi)部類。當(dāng)接收到底層的 VSync 信號開始處理 UI 過程。VSync 信號由 SurfaceFlinger 實現(xiàn)并定時發(fā)送。FrameDisplayEventReceiver 收到信號后,調(diào)用 onVsync 方法組織消息發(fā)送到主線程處理。這個消息主要內(nèi)容就是 run 方法里面的 doFrame 了,這里 mTimestampNanos 是信號到來的時間參數(shù)。
那么 FrameDisplayEventReceiver 是通過什么方式在 Vsync 信號到來的時候回調(diào) onVsync 呢?答案是 FrameDisplayEventReceiver 的初始化的時候,最終通過監(jiān)聽文件句柄的形式,其對應(yīng)的初始化流程如下
// android/view/Choreographer.java private Choreographer(Looper looper, int vsyncSource) { mLooper = looper; mDisplayEventReceiver = USE_VSYNC ? new FrameDisplayEventReceiver(looper, vsyncSource) : null; ...... } // android/view/Choreographer.java public FrameDisplayEventReceiver(Looper looper, int vsyncSource) { super(looper, vsyncSource); } // android/view/DisplayEventReceiver.java public DisplayEventReceiver(Looper looper, int vsyncSource) { ...... mMessageQueue = looper.getQueue(); mReceiverPtr = nativeInit(new WeakReference<DisplayEventReceiver>(this), mMessageQueue, vsyncSource); }
nativeInit 后續(xù)的代碼可以自己跟一下,可以對照這篇文章和源碼,由于篇幅比較多,這里就不細說了。
簡單來說,F(xiàn)rameDisplayEventReceiver 的初始化過程中,通過 BitTube (本質(zhì)是一個 socket pair),來傳遞和請求 Vsync 事件,當(dāng) SurfaceFlinger 收到 Vsync 事件之后,通過 appEventThread 將這個事件通過 BitTube 傳給 DisplayEventDispatcher ,DisplayEventDispatcher 通過 BitTube 的接收端監(jiān)聽到 Vsync 事件之后,回調(diào) Choreographer.FrameDisplayEventReceiver.onVsync ,觸發(fā)開始一幀的繪制。
如下圖
4.3、ChoreoGrapher 的總體流程
FrameHandler 和 FrameDisplayEventReceiver 是怎么工作的呢?ChoreoGrapher 的總體流程圖如下圖(拷貝的圖片):
以上是總體的流程圖:
1.PostCallBack orpostFrameCallback發(fā)起添加回調(diào),這個FrameCallBack將在下一幀被渲染時執(zhí)行。
2.AddToCallBackQueue,將 FrameCallBack 添加到回調(diào)隊列里面,等待時機執(zhí)行回調(diào)。每種類型的callback按照設(shè)置的執(zhí)行時間(dueTime)順序排序分別保存在一個單鏈表中。
3.判斷 FrameCallBack設(shè)定的執(zhí)行時間是否在當(dāng)前時間之后,若是,發(fā)送 MSG_DO_SCHEDULE_CALLBACK 消息到主線程,安排執(zhí)行doScheduleCallback,安排執(zhí)行CallBack。否則直接跳到第4步。
4.執(zhí)行 scheduleFrameLocked,安排執(zhí)行下一幀。
5.判斷上一幀是否已經(jīng)執(zhí)行,若未執(zhí)行,當(dāng)前操作直接結(jié)束。若已經(jīng)執(zhí)行,根據(jù)情況執(zhí)行以下6、7步。
6.若使用垂直同步信號進行同步,則執(zhí)行7.否則,直接跳到9。
7.若當(dāng)前線程是UI線程,則通過執(zhí)行scheduleVsyncLocked請求垂直同步信號。否則,送MSG_DO_SCHEDULE_VSYNC消息到主線程,安排執(zhí)行doScheduleVsync,在主線程調(diào)用scheduleVsyncLocked。
8.收到垂直同步信號,調(diào)用FrameDisplayEventReceiver.onVsync(),發(fā)送消息到主線程,請求執(zhí)行doFrame。
9.執(zhí)行doFrame,渲染下一幀。
主要的工作在 doFrame 中,接下來我們具體看看 doFrame 函數(shù)都干了些什么。
從名字看很容易理解 doFrame 函數(shù)就是開始進行下一幀的顯示工作。好了以下源代碼又來了,我們一行一行分析一下吧。
4.4、doFrame
@UnsupportedAppUsage void doFrame(long frameTimeNanos, int frame) { final long startNanos; synchronized (mLock) { // 為false, 說明還未開始 if (!mFrameScheduled) { return; // no work to do } if (DEBUG_JANK && mDebugPrintNextFrameTimeDelta) { mDebugPrintNextFrameTimeDelta = false; Log.d(TAG, "Frame time delta: " + ((frameTimeNanos - mLastFrameTimeNanos) * 0.000001f) + " ms"); } long intendedFrameTimeNanos = frameTimeNanos; startNanos = System.nanoTime(); // 計算當(dāng)前時間與 vsync 信號的時間差 final long jitterNanos = startNanos - frameTimeNanos; // 說明出現(xiàn)掉幀情況,注意只有 jitterNanos 大于 16.6 ms 才說明掉幀,否則只是輕微的延遲。 if (jitterNanos >= mFrameIntervalNanos) { final long skippedFrames = jitterNanos / mFrameIntervalNanos; if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) { Log.i(TAG, "Skipped " + skippedFrames + " frames! " + "The application may be doing too much work on its main thread."); } // 當(dāng)發(fā)生掉幀后,需要計算被耽誤的時間。比如處理了 36.6ms, 一個周期是 16.6 ms, 相當(dāng)于延遲了 3.4 ms 執(zhí)行 final long lastFrameOffset = jitterNanos % mFrameIntervalNanos; if (DEBUG_JANK) { Log.d(TAG, "Missed vsync by " + (jitterNanos * 0.000001f) + " ms " + "which is more than the frame interval of " + (mFrameIntervalNanos * 0.000001f) + " ms! " + "Skipping " + skippedFrames + " frames and setting frame " + "time to " + (lastFrameOffset * 0.000001f) + " ms in the past."); } // 修正當(dāng)前幀的時間 = 開始時間 - 耽誤時間 frameTimeNanos = startNanos - lastFrameOffset; } // 當(dāng)前時間小于前一幀時間,不執(zhí)行操作 if (frameTimeNanos < mLastFrameTimeNanos) { if (DEBUG_JANK) { Log.d(TAG, "Frame time appears to be going backwards. May be due to a " + "previously skipped frame. Waiting for next vsync."); } // 直接請求下一個 vsync 信號 scheduleVsyncLocked(); return; } // 大于 1 說明采用的默認幀數(shù)的一半,因此需要根據(jù)時間間隔來判斷是否有必要執(zhí)行繪制 if (mFPSDivisor > 1) { long timeSinceVsync = frameTimeNanos - mLastFrameTimeNanos; if (timeSinceVsync < (mFrameIntervalNanos * mFPSDivisor) && timeSinceVsync > 0) { // 時間間隔小于指定的時間,繼續(xù)請求下一個 vsync 信號 scheduleVsyncLocked(); return; } } // 保存當(dāng)前幀的相關(guān)信息 mFrameInfo.setVsync(intendedFrameTimeNanos, frameTimeNanos); mFrameScheduled = false; mLastFrameTimeNanos = frameTimeNanos; } try { // 執(zhí)行相關(guān) callbacks Trace.traceBegin(Trace.TRACE_TAG_VIEW, "Choreographer#doFrame"); AnimationUtils.lockAnimationClock(frameTimeNanos / TimeUtils.NANOS_PER_MS); mFrameInfo.markInputHandlingStart(); doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos); mFrameInfo.markAnimationsStart(); doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos); doCallbacks(Choreographer.CALLBACK_INSETS_ANIMATION, frameTimeNanos); mFrameInfo.markPerformTraversalsStart(); doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos); doCallbacks(Choreographer.CALLBACK_COMMIT, frameTimeNanos); } finally { AnimationUtils.unlockAnimationClock(); Trace.traceEnd(Trace.TRACE_TAG_VIEW); } if (DEBUG_FRAMES) { final long endNanos = System.nanoTime(); Log.d(TAG, "Frame " + frame + ": Finished, took " + (endNanos - startNanos) * 0.000001f + " ms, latency " + (startNanos - frameTimeNanos) * 0.000001f + " ms."); } }
總結(jié)起來其實主要是兩個操作:
4.4.1、設(shè)置當(dāng)前 frame 的啟動時間
判斷是否跳幀,若跳幀修正當(dāng)前 frame 的啟動時間到最近的 VSync 信號時間。如果沒跳幀,當(dāng)前 frame 啟動時間直接設(shè)置為當(dāng)前 VSync 信號時間。修正完時間后,無論當(dāng)前 frame 是否跳幀,使得當(dāng)前 frame 的啟動時間與 VSync 信號還是在一個節(jié)奏上的,可能延后了一到幾個周期,但是都是在下一個 vsync 信號到來才進行處理 。
如下圖所示是時間修正的一個例子,
沒有跳幀但延遲
由于第二個 frame 執(zhí)行超時,第三個 frame 實際啟動時間比第三個 VSync 信號到來時間要晚,因為這時候延時比較小,沒有超過一個時鐘周期,系統(tǒng)還是將 frameTimeNanos3 傳給回調(diào),回調(diào)拿到的時間和 VSync 信號同步。
再來看看下圖:
跳幀
由于第二個 frame執(zhí)行時間超過 2 個時鐘周期,導(dǎo)致第三個 frame 延后執(zhí)行時間大于一個時鐘周期,系統(tǒng)認為這時候影響較大,判定為跳幀了,將第三個 frame 的時間修正為 frameTimeNanos4,比 VSync 真正到來的時間晚了一個時鐘周期。
時間修正,既保證了doFrame操作和 VSync 保持同步節(jié)奏,又保證實際啟動時間與記錄的時間點相差不會太大,便于同步及分析。
4.4.2、順序執(zhí)行callBack隊列里面的callback
然后接下來看看 doCallbacks 的執(zhí)行過程:
void doCallbacks(int callbackType, long frameTimeNanos) { CallbackRecord callbacks; synchronized (mLock) { // We use "now" to determine when callbacks become due because it's possible // for earlier processing phases in a frame to post callbacks that should run // in a following phase, such as an input event that causes an animation to start. final long now = System.nanoTime(); // callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked( now / TimeUtils.NANOS_PER_MS); if (callbacks == null) { return; } mCallbacksRunning = true; // Update the frame time if necessary when committing the frame. // We only update the frame time if we are more than 2 frames late reaching // the commit phase. This ensures that the frame time which is observed by the // callbacks will always increase from one frame to the next and never repeat. // We never want the next frame's starting frame time to end up being less than // or equal to the previous frame's commit frame time. Keep in mind that the // next frame has most likely already been scheduled by now so we play it // safe by ensuring the commit time is always at least one frame behind. // commit 類型是最后執(zhí)行的,如果此時發(fā)現(xiàn)前面處理時間過長,就會進行糾正。 if (callbackType == Choreographer.CALLBACK_COMMIT) { final long jitterNanos = now - frameTimeNanos; Trace.traceCounter(Trace.TRACE_TAG_VIEW, "jitterNanos", (int) jitterNanos); if (jitterNanos >= 2 * mFrameIntervalNanos) { final long lastFrameOffset = jitterNanos % mFrameIntervalNanos + mFrameIntervalNanos; if (DEBUG_JANK) { Log.d(TAG, "Commit callback delayed by " + (jitterNanos * 0.000001f) + " ms which is more than twice the frame interval of " + (mFrameIntervalNanos * 0.000001f) + " ms! " + "Setting frame time to " + (lastFrameOffset * 0.000001f) + " ms in the past."); mDebugPrintNextFrameTimeDelta = true; } frameTimeNanos = now - lastFrameOffset; mLastFrameTimeNanos = frameTimeNanos; } } } try { Trace.traceBegin(Trace.TRACE_TAG_VIEW, CALLBACK_TRACE_TITLES[callbackType]); for (CallbackRecord c = callbacks; c != null; c = c.next) { if (DEBUG_FRAMES) { Log.d(TAG, "RunCallback: type=" + callbackType + ", action=" + c.action + ", token=" + c.token + ", latencyMillis=" + (SystemClock.uptimeMillis() - c.dueTime)); } // 運行每一個 callback c.run(frameTimeNanos); } } finally { synchronized (mLock) { mCallbacksRunning = false; do { final CallbackRecord next = callbacks.next; recycleCallbackLocked(callbacks); callbacks = next; } while (callbacks != null); } Trace.traceEnd(Trace.TRACE_TAG_VIEW); } }
callback的類型有以下 4 種,除了文章一開始提到的 3 種外,還有一個 CALLBACK_COMMIT。
- CALLBACK_INPUT:輸入
- CALLBACK_ANIMATION:動畫
- CALLBACK_TRAVERSAL:遍歷,執(zhí)行 measure、layout、draw
- CALLBACK_COMMIT:遍歷完成的提交操作,用來修正動畫啟動時間
然后看上面的源碼,分析一下每個 callback 的執(zhí)行過程:
1. callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked( now / TimeUtils.NANOS_PER_MS);
得到執(zhí)行時間在當(dāng)前時間之前的所有 CallBack,保存在單鏈表中。每種類型的 callback 按執(zhí)行時間先后順序排序分別存在一個單鏈表里面。為了保證當(dāng)前 callback 執(zhí)行時新 post 進來的 callback 在下一個 frame 時才被執(zhí)行,這個地方 extractDueCallbacksLocked 會將需要執(zhí)行的 callback 和以后執(zhí)行的 callback 斷開變成兩個鏈表,新 post 進來的 callback 會被放到后面一個鏈表中。當(dāng)前 frame 只會執(zhí)行前一個鏈表中的 callback,保證了在執(zhí)行 callback 時,如果callback中Post相同類型的callback,這些新加的 callback 將在下一個 frame 啟動后才會被執(zhí)行。
2. 接下來,看一大段注釋,如果類型是 CALLBACK_COMMIT,并且當(dāng)前 frame 渲染時間超過了兩個時鐘周期,則將當(dāng)前提交時間修正為上一個垂直同步信號時間。為了保證下一個frame 的提交時間和當(dāng)前 frame 時間相差為一且不重復(fù)。
這個地方注釋挺難看懂,實際上這個地方 CALLBACK_COMMIT 是為了解決 ValueAnimator 的一個問題而引入的,主要是解決因為遍歷時間過長導(dǎo)致動畫時間啟動過長,時間縮短,導(dǎo)致跳幀,這里修正動畫第一個 frame 開始時間延后來改善,這時候才表示動畫真正啟動。為什么不直接設(shè)置當(dāng)前時間而是回溯一個時鐘周期之前的時間呢?看注釋,這里如果設(shè)置為當(dāng)前 frame 時間,因為動畫的第一個 frame 其實已經(jīng)繪制完成,第二個 frame 這時候已經(jīng)開始了,設(shè)置為當(dāng)前時間會導(dǎo)致這兩個 frame 時間一樣,導(dǎo)致沖突。
如下圖所示:
修正commit時間
比如說在第二個frame開始執(zhí)行時,開始渲染動畫的第一個畫面,第二個frame執(zhí)行時間超過了兩個時鐘周期,Draw操作執(zhí)行結(jié)束后,這時候完成了動畫第一幀的渲染,動畫實際上還沒開始,但是時間已經(jīng)過了兩個時鐘周期,后面動畫實際執(zhí)行時間將會縮短一個時鐘周期。這時候系統(tǒng)通過修正commit時間到frameTimeNanos的上一個VSync信號時間,即完成動畫第一幀渲染之前的VSync信號到來時間,修正了動畫啟動時間,保證動畫執(zhí)行時間的正確性。
4.4.3、調(diào)用 c.run(frameTimeNanos) 執(zhí)行回調(diào)
private static final class CallbackRecord { public CallbackRecord next; public long dueTime; public Object action; // Runnable or FrameCallback public Object token; @UnsupportedAppUsage public void run(long frameTimeNanos) { if (token == FRAME_CALLBACK_TOKEN) { ((FrameCallback)action).doFrame(frameTimeNanos); } else { ((Runnable)action).run(); } } }
CallbackRecord 的代碼如上所示。
4.5、發(fā)起繪制的請求
doFrame 的邏輯了解清楚了,但是關(guān)于發(fā)起 vsync 請求的邏輯卻沒有講。
// ViewRootImpl @UnsupportedAppUsage void scheduleTraversals() { // 如果已經(jīng)請求繪制了,就不會再次請求,因為多次請求,只有有一個執(zhí)行就滿足要求了 if (!mTraversalScheduled) { mTraversalScheduled = true;// 同步 mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); // 發(fā)送一個 callback 用于在下一幀來臨時候處理 mChoreographer.postCallback( Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); if (!mUnbufferedInputDispatch) { scheduleConsumeBatchedInput(); } // 通知稍候繪制 notifyRendererOfFramePending(); pokeDrawLockIfNeeded(); } }
接著會調(diào)用postCallbackDelayed:
public void postCallbackDelayed(int callbackType, Runnable action, Object token, long delayMillis) { if (action == null) { throw new IllegalArgumentException("action must not be null"); } if (callbackType < 0 || callbackType > CALLBACK_LAST) { throw new IllegalArgumentException("callbackType is invalid"); } postCallbackDelayedInternal(callbackType, action, token, delayMillis); }
主要是做一些邏輯判斷,確保傳入的是對的。
接著又會調(diào)用postCallbackDelayedInternal,保存 callback,并發(fā)起請求下一幀。
private void postCallbackDelayedInternal(int callbackType, Object action, Object token, long delayMillis) { if (DEBUG_FRAMES) { Log.d(TAG, "PostCallback: type=" + callbackType + ", action=" + action + ", token=" + token + ", delayMillis=" + delayMillis); } synchronized (mLock) { final long now = SystemClock.uptimeMillis(); final long dueTime = now + delayMillis; mCallbackQueues[callbackType].addCallbackLocked(dueTime, action, token); // 小于當(dāng)前時間,說明需要立即執(zhí)行 if (dueTime <= now) { scheduleFrameLocked(now); } else { // 發(fā)送一個延遲 msg Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action); msg.arg1 = callbackType; msg.setAsynchronous(true); mHandler.sendMessageAtTime(msg, dueTime); } } }
簡單來說,就是判斷當(dāng)前是否有必要發(fā)起一個繪制請求,比如你發(fā)了一個 500ms 后重繪的消息,對于這個消息,會在 500ms 后在進行處理。但如果不是延遲消息,那說明需要立即處理。但是對于 view 的繪制邏輯,必須得等到下一個 vsync 到來的時候才會真正進行繪制。
接下來看看scheduleFrameLocked 的邏輯:
private void scheduleFrameLocked(long now) { if (!mFrameScheduled) { mFrameScheduled = true; if (USE_VSYNC) { if (DEBUG_FRAMES) { Log.d(TAG, "Scheduling next frame on vsync."); } // If running on the Looper thread, then schedule the vsync immediately, // otherwise post a message to schedule the vsync from the UI thread // as soon as possible. // 如果是在一個 looper 線程中,那么直接執(zhí)行請求就好 if (isRunningOnLooperThreadLocked()) { scheduleVsyncLocked(); } else { // 如果是在主線程,那么需要發(fā)送一個請求 vsync 的消息,并插到最前面,需要確保前一個消息處理完后在開始請求 Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC); msg.setAsynchronous(true); mHandler.sendMessageAtFrontOfQueue(msg); } } else { // 如果不用 vsync 信號,那么就可以直接執(zhí)行,只是需要記錄每一幀的時間 final long nextFrameTime = Math.max( mLastFrameTimeNanos / TimeUtils.NANOS_PER_MS + sFrameDelay, now); if (DEBUG_FRAMES) { Log.d(TAG, "Scheduling next frame in " + (nextFrameTime - now) + " ms."); } Message msg = mHandler.obtainMessage(MSG_DO_FRAME); msg.setAsynchronous(true); mHandler.sendMessageAtTime(msg, nextFrameTime); } } }
這里主要是根據(jù)具體情況來判斷如何發(fā)起下一幀的繪制。對于采用 vsync 信號的主線程,會發(fā)送一個MSG_DO_SCHEDULE_VSYNC 的消息,插到最前面,確??梢宰钤鐖?zhí)行。
當(dāng)收到 MSG_DO_SCHEDULE_VSYNC 消息后,就會給他安排請求 vsync 信號的請求,最后會會調(diào)到 onVsync 方法。
void doScheduleVsync() { synchronized (mLock) { if (mFrameScheduled) { scheduleVsyncLocked(); } } } @UnsupportedAppUsage private void scheduleVsyncLocked() { // 發(fā)起獲取 vsync 信號的請求 mDisplayEventReceiver.scheduleVsync(); } /** * Schedules a single vertical sync pulse to be delivered when the next * display frame begins. */ @UnsupportedAppUsage public void scheduleVsync() { if (mReceiverPtr == 0) { Log.w(TAG, "Attempted to schedule a vertical sync pulse but the display event " + "receiver has already been disposed."); } else { nativeScheduleVsync(mReceiverPtr); } }
到這里,就把Choreographer 的基本原理都講完了。
五、源碼小結(jié)
Choreographer是線程單例的,而且必須要和一個 Looper 綁定,因為其內(nèi)部有一個 Handler 需要和 Looper 綁定,一般是 App 主線程的 Looper 綁定。
DisplayEventReceiver是一個 abstract class,其 JNI 的代碼部分會創(chuàng)建一個IDisplayEventConnection 的 Vsync 監(jiān)聽者對象。這樣,來自 AppEventThread 的 VSYNC 中斷信號就可以傳遞給 Choreographer 對象了。當(dāng) Vsync 信號到來時,DisplayEventReceiver 的 onVsync 函數(shù)將被調(diào)用。
DisplayEventReceiver還有一個 scheduleVsync 函數(shù)。當(dāng)應(yīng)用需要繪制UI時,將首先申請一次 Vsync 中斷,然后再在中斷處理的 onVsync 函數(shù)去進行繪制。
Choreographer定義了一個FrameCallbackinterface,每當(dāng) Vsync 到來時,其 doFrame 函數(shù)將被調(diào)用。這個接口對 Android Animation 的實現(xiàn)起了很大的幫助作用。以前都是自己控制時間,現(xiàn)在終于有了固定的時間中斷。
Choreographer的主要功能是,當(dāng)收到 Vsync 信號時,去調(diào)用使用者通過 postCallback 設(shè)置的回調(diào)函數(shù)。目前一共定義了五種類型的回調(diào),它們分別是:ListView的 Item 初始化(obtain\setup) 會在 input 里面也會在 animation 里面,這取決于
- CALLBACK_INPUT: 處理輸入事件處理有關(guān)
- CALLBACK_ANIMATION: 處理 Animation 的處理有關(guān)
- CALLBACK_INSETS_ANIMATION: 處理 Insets Animation 的相關(guān)回調(diào)
- CALLBACK_TRAVERSAL: 處理和 UI 等控件繪制有關(guān)
- CALLBACK_COMMIT: 處理 Commit 相關(guān)回調(diào)
CALLBACK_INPUT、CALLBACK_ANIMATION會修改 view 的屬性,所以要比 CALLBACK_TRAVERSAL 先執(zhí)行
最后附上一張時序圖,來回顧一下整個流程
以上就是分析Android Choreographer源碼的詳細內(nèi)容,更多關(guān)于Android Choreographer的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
View事件分發(fā)原理和ViewPager+ListView嵌套滑動沖突
這篇文章主要介紹了View事件分發(fā)原理和ViewPager+ListView嵌套滑動沖突,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價,需要的小伙伴可以參考一下2022-05-05Android下拉刷新完全解析,教你如何一分鐘實現(xiàn)下拉刷新功能(附源碼)
以下是我自己花功夫編寫了一種非常簡單的下拉刷新實現(xiàn)方案,現(xiàn)在拿出來和大家分享一下。相信在閱讀完本篇文章之后,大家都可以在自己的項目中一分鐘引入下拉刷新功能2013-07-07Android系統(tǒng)檢測程序內(nèi)存占用各種方法
這篇文章主要介紹了Android系統(tǒng)檢測程序內(nèi)存占用各種方法,本文講解了檢查系統(tǒng)總內(nèi)存、檢查某個程序的各類型內(nèi)存占用、檢查程序狀態(tài)、檢查程序各部分的內(nèi)存占用等內(nèi)容,需要的朋友可以參考下2015-03-03Android 消息分發(fā)使用EventBus的實例詳解
這篇文章主要介紹了Android 消息分發(fā)使用EventBus的實例詳解的相關(guān)資料,在項目中用了許多Handler和broadcast導(dǎo)致代碼冗余,顯得雜亂無章,這里使用EventBus來實現(xiàn)相同的功能,需要的朋友可以參考下2017-07-07android開發(fā)之橫向滾動/豎向滾動的ListView(固定列頭)
由于項目需要,我們需要一個可以橫向滾動的,又可以豎向滾動的 表格;經(jīng)過幾天的研究終于搞定,感興趣的朋友可以了解下哦2013-01-01Android Flutter實現(xiàn)GIF動畫效果的方法詳解
如果我們想對某個組件實現(xiàn)一組動效應(yīng)該怎么辦呢?本文將利用Android Flutter實現(xiàn)GIF動畫效果,文中的示例代碼講解詳細,需要的可以參考一下2022-06-06