Android屏幕刷新机制(一):屏幕刷新发生了什么

参考

文章完全参考自:Android 屏幕刷新机制

不过原文是从源码揭秘的角度从代码调用的层面层层深入到了底层,教着看源码摸原理。本文倒着来,直接说了原理,然后按着Android系统的步骤看代码是怎么走的。

开始

硬件——屏幕发送信号

Android 屏幕每16.6ms刷新一次【60fps,即1000ms/60f = 16.6ms】。也就是屏幕【Display】每隔16ms就会发出一次VSYNC信号。

image-20201031131730052

系统——接收屏幕传来的VSync信号

接收此信号系统类叫DisplayEventReceiver,是个抽象类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Provides a low-level mechanism for an application to receive display events
* such as vertical sync.
*
* The display event receive is NOT thread safe. Moreover, its methods must only
* be called on the Looper thread to which it is attached.
*
* @hide
*/
public abstract class DisplayEventReceiver {
...
/**
* Called when a vertical sync pulse is received.
* 在VSync脉冲到达时会被调用
* The recipient should render a frame and then call {@link #scheduleVsync}
* 接受者应该rende a frame(渲染好框架?)并调用 #scheduleVsync
* to schedule the next vertical sync pulse.
*/
@UnsupportedAppUsage
public void onVsync(long timestampNanos, long physicalDisplayId, int frame) {
}

...

/**
* Schedules a single vertical sync pulse to be delivered when the next
* display frame begins.
* 在下一帧到来前Schedules(规划)一个 用于被接收的 VSync脉冲
*/
@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);
}
}

...


}

其中两个方法:onVsync是接收到脉冲信息时的回调,注释告诉我们在这之前会先调用scheduleVsyncscheduleVsync相当于对即将到来的下一帧注册了一个监听,只有注册了,下一帧才会调用到onVsync方法中来。

具体实现这个抽象类的是FrameDisplayEventReceiver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private final class FrameDisplayEventReceiver extends DisplayEventReceiver implements Runnable {
@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);
}
}

可以看到onVsync中接收到信号后创建了一个Message,将自身(this)传了进去【因为自身实现了Runnable接口】。再通过mHandler发了出去。mHandler是一个FrameHandler,所以要去看FrameHandler

用Handler传递消息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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://0
doFrame(System.nanoTime(), 0);
break;
case MSG_DO_SCHEDULE_VSYNC://1
doScheduleVsync();
break;
case MSG_DO_SCHEDULE_CALLBACK://2
doScheduleCallback(msg.arg1);
break;
}
}
}

显然,传入的msg未设置msg,所以msg为0。走doFrame(System.nanoTime(), 0);

走错了,因为Handler 在处理消息时会先查看 Message 是否有 callback,有则优先交由 Message 的 callback 处理消息,没有的话再去看看Handler 有没有 callback,如果也没有才会交由 handleMessage() 这个方法执行。

所以这里会直接执行doFrame()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
void doFrame(long frameTimeNanos, int frame) {
final long startNanos;
synchronized (mLock) {
...
mFrameInfo.setVsync(intendedFrameTimeNanos, frameTimeNanos);
mFrameScheduled = false;
mLastFrameTimeNanos = frameTimeNanos;
}

try {
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);
}

}

doFrame代码有点长,里面有一段try catch 包裹的代码,不停的在doCallbacks(int,long)。源码往下滑两行就发现doCallbacks就在下面。

Handler收到消息走doFrame,又走doCallbacks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
callbacks = mCallbackQueues[callbackType].extractDueCallbacksLocked(
now / TimeUtils.NANOS_PER_MS);
if (callbacks == null) {
return;
}
mCallbacksRunning = true;
...
}
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.run
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);
}
}

① mCallbackQueues

mCallbackQueues的第callbackType个元素中,提取一个callback【extractDueCallbacksLocked()】。

mCallbackQueues是一个长度为5的队列,存的是元素CallbackQueue

1
2
3
4
mCallbackQueues = new CallbackQueue[CALLBACK_LAST + 1];
for (int i = 0; i <= CALLBACK_LAST; i++) {
mCallbackQueues[i] = new CallbackQueue();
}

CallbackQueue听名字又是一个队列。没错,就是队列中存放着队列。CallbackQueue中存放的元素是CallbackRecord,链表的形式。所以大概是这个样子:

image-20201101151630877

②c.run(frameTimeNanos);

取出来是一串链子(callbacks),所以一个for循环,循环调用run方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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();
}
}
}

嗯?token是啥?action是啥?接下来怎么走??不知道。因为这个CallbackRecord又不是我们加进来的,至少在上面分析的代码中没看到add操作。

总结:屏幕刷新发生了什么

屏幕每16.6ms向系统层面发送一个VSync信号,系统在FrameDisplayEventReceiveronVsync()里通过Handler发送了个Message(把FrameDisplayEventReceiver自己作为runnable传了进去)。Handler中收到message后就调用doFrame中的doCallbacks方法,从一个**链表组成的列表(CallbackQueue)**中取链子(CallbackRecord),然后调用每个链子(CallbackRecord`)的run方法。