// vsync for a particular display.
// At this time Surface Flinger won’t send us vsyncs for secondary displays
// but that could change in the future so let’s log a message to help us remember
// that we need to fix this.
if (builtInDisplayId != SurfaceControl.BUILT_IN_DISPLAY_ID_MAIN) {
Log.d(TAG, "Received vsync from secondary display, but we don’t support "
-
"this case yet. Choreographer needs a way to explicitly request "
-
"vsync for a specific display to ensure it doesn’t lose track "
-
“of its scheduled vsync.”);
scheduleVsync();
return;
}
// 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);
}
注意看下timestampNanos的参数(简单来说就是从调用native方法以后到回调到这个方法所经过的的时间)
接着看会发送一条异步消息,简单来说就是此消息在消息队列中不用排队,可以最先被取出来,很明显,会调用下面的run方法进行处
@Override
public void run() {
mHavePendingVsync = false;
doFrame(mTimestampNanos, mFrame);
}
这里调用的doframe方法
void doFrame(long frameTimeNanos, int frame) {
final long startNanos;
synchronized (mLock) {
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();
final long jitterNanos = startNanos - frameTimeNanos;
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.”);
}
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.”);
}
frameTimeNanos = startNanos - lastFrameOffset;
}
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.”);
}
scheduleVsyncLocked();
return;
}
if (mFPSDivisor > 1) {
long timeSinceVsync = frameTimeNanos - mLastFrameTimeNanos;
if (timeSinceVsync < (mFrameIntervalNanos * mFPSDivisor) && timeSinceVsync > 0) {
scheduleVsyncLocked();
return;
}
}
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);
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.");
}
}
有几个重点的地方要说下,我们开发时偶尔在log上会看到Skipped " + skippedFrames + " frames! "
+ "The application may be doing too much work on its main thread."这句话,很多人以为出现这句话是因为ui线程太耗时了,其实仔细想想就知道是错的,因为在回掉这方法的时候根本没有执行到
测量,绘制等,它的两个时间对比的是回掉到此帧的时间frameTimeNanos和当前的时间,如果大于16.66ms就会打印这句话,那就是说执行native方法到onFrame回掉超过16.66ms,而onFrame回掉是通过异步消息,可以忽略不计,那唯一可能出现的情况就是通过handler后执行dispatchVsync方法,与执行native方法的耗时,也就是说此时会有多个message,而执行dispatchVsync方法的message是排在比较后面的,这也解释了这句log:he application may be doing too much work on its main thread.
所以这句话并不能判断是ui卡顿了,只能说明有很多message,要减少不必要的message才是优化的根本。
而frameTimeNanos = startNanos - lastFrameOffset;简单来说就是给vsnc设置帧数的偏移量
那又是啥意思呢?
比如我在第一帧发起了重绘制,按理来说第二帧就会收到Vsync的信号值,但是由于message阻塞了超过了16.66,所以收到Vsync的信号自然延续要了第三帧。
在了解这句话以后,接下来就是回调绘制,或者input事件了,可以看到代码会间接调用doCallbacks
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.
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));
}
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);
}
}
从而执行 c.run(frameTimeNanos);方法进行回调
这里放张图,大家可以理解一下
简单说下
一开始注册了vsync信号,所以在下一帧调用了dispatchVsync方法,由于没有message阻塞,所以接收到了此帧的信号,进行了绘制,在绘制完成后又注册了信号,可以看到一帧内注册同一信号是无效的,但是回掉会执行,到了下一帧,由于message的超时不到16.66ms,所以也就是执行dispatchVsync与执行native方法的间隔时间,所以还是此帧还是有信号的,而由于此帧耗时超过了一帧,所以没有注册Vsync,当然也不会执行dispatchVsync方法,到了最后可以看到由于message超过了16.66即使在第三帧注册了Vsync信号,但是dispatchVsync执行的事件已经到了第5帧
卡顿优化
在简单分析完了Choreographer机制以后,来具体说下卡顿优化的两种方案的原理
1、 利用UI线程的Looper打印的日志匹配;
2、 使用Choreographer.FrameCallback
第一种是blockcanary的原理,就是利用looper.loop分发事件的时间间隔作为卡顿的依据
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException(“No Looper; Looper.prepare() wasn’t called on this thread.”);
}
final MessageQueue queue = me.mQueue;
// Make sure the identity of this thread is that of the local process,
// and keep track of what that identity token actually is.
Binder.clearCallingIdentity();
final long ident = Binder.clearCallingIdentity();
// Allow overriding a threshold with a system prop. e.g.
// adb shell ‘setprop log.looper.1000.main.slow 1 && stop && start’
final int thresholdOverride =
SystemProperties.getInt(“log.looper.”
-
Process.myUid() + “.”
-
Thread.currentThread().getName()
-
“.slow”, 0);
boolean slowDeliveryDetected = false;
for (;😉 {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
// This must be in a local variable, in case a UI event sets the logger
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
final long traceTag = me.mTraceTag;
long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
if (thresholdOverride > 0) {
slowDispatchThresholdMs = thresholdOverride;
slowDeliveryThresholdMs = thresholdOverride;
}
final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);
final boolean needStartTime = logSlowDelivery || logSlowDispatch;
final boolean needEndTime = logSlowDispatch;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
final long dispatchEnd;
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
if (logSlowDelivery) {
if (slowDeliveryDetected) {
if ((dispatchStart - msg.when) <= 10) {
Slog.w(TAG, “Drained”);
slowDeliveryDetected = false;
}
} else {
if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, “delivery”,
msg)) {
// Once we write a slow delivery log, suppress until the queue drains.
slowDeliveryDetected = true;
}
}
}
if (logSlowDispatch) {
showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, “dispatch”, msg);
}
if (logging != null) {
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
…
也就是对logging进行深入的研究,一般超过了1000ms就认为卡顿了,但我们有没有想过,我们通常说的卡顿不是说超过了16.66ms么,为何这里要超过500ms,甚至1000ms才算是卡顿?
我们要知道,android系统所有的执行都是基于looper机制的,也就是所有的消息执行的时间超过1000ms就认定卡顿了,举个例子,我们可能在主线程操作数据库,可能在主线程解析json,可能在主线程写文件,可能在主线程做一些例如高斯模糊的耗时操作
这种情况下我们利用blockcanary是可以检测出来的,但是如果是卡顿呢?当然我们也可以把时间设定为50ms,但是检测出来的太多了,所以就需要第二个机制了Choreographer.FrameCallback,通常这样写
public class BlockDetectByChoreographer {
public static void start() {
Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
long lastFrameTimeNanos = 0;
long currentFrameTimeNanos = 0;
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
重要知识点
下面是有几位Android行业大佬对应上方技术点整理的一些进阶资料。
高级进阶篇——高级UI,自定义View(部分展示)
UI这块知识是现今使用者最多的。当年火爆一时的Android入门培训,学会这小块知识就能随便找到不错的工作了。不过很显然现在远远不够了,拒绝无休止的CV,亲自去项目实战,读源码,研究原理吧!
- 面试题部分合集
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!**
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
重要知识点
下面是有几位Android行业大佬对应上方技术点整理的一些进阶资料。
[外链图片转存中…(img-iVEFaUTR-1713299949569)]
高级进阶篇——高级UI,自定义View(部分展示)
UI这块知识是现今使用者最多的。当年火爆一时的Android入门培训,学会这小块知识就能随便找到不错的工作了。不过很显然现在远远不够了,拒绝无休止的CV,亲自去项目实战,读源码,研究原理吧!
[外链图片转存中…(img-6ATHjwID-1713299949570)]
- 面试题部分合集
[外链图片转存中…(img-jBkGjag0-1713299949571)]
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!