Choreographer机制和卡顿优化(1),Android开发者出路在哪

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) {

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
img

如何成为Android高级架构师!

架构师必须具备抽象思维和分析的能力,这是你进行系统分析和系统分解的基本素质。只有具备这样的能力,架构师才能看清系统的整体,掌控全局,这也是架构师大局观的形成基础。 你如何具备这种能力呢?一是来自于经验,二是来自于学习。

架构师不仅要具备在问题领域上的经验,也需要具备在软件工程领域内的经验。也就是说,架构师必须能够准确得理解需求,然后用软件工程的思想,把需求转化和分解成可用计算机语言实现的程度。经验的积累是需要一个时间过程的,这个过程谁也帮不了你,是需要你去经历的。

但是,如果你有意识地去培养,不断吸取前人的经验的话,还是可以缩短这个周期的。这也是我整理架构师进阶此系列的始动力之一。


成为Android架构师必备知识技能

对应导图的学习笔记(由阿里P8大牛手写,我负责整理成PDF笔记)

部分内容展示

《设计思想解读开源框架》

  • 目录
  • 热修复设计
  • 插件化框架设计

    《360°全方面性能优化》
  • 设计思想与代码质量优化
  • 程序性能优化

架构师必备知识技能

[外链图片转存中…(img-Sm6Z22kW-1710656266208)]

对应导图的学习笔记(由阿里P8大牛手写,我负责整理成PDF笔记)

[外链图片转存中…(img-ZlM3W4es-1710656266209)]

部分内容展示

《设计思想解读开源框架》

  • 目录
    [外链图片转存中…(img-bIgn4CCa-1710656266209)]
  • 热修复设计
    [外链图片转存中…(img-nLrLWKKx-1710656266209)]
  • 插件化框架设计
    [外链图片转存中…(img-dF2XnDgm-1710656266210)]
    《360°全方面性能优化》
    [外链图片转存中…(img-A6v7PHYo-1710656266210)]
  • 设计思想与代码质量优化
    [外链图片转存中…(img-EuCevPh0-1710656266210)]
  • 程序性能优化
    [外链图片转存中…(img-leJ0sAj8-1710656266211)]

本文在开源项目:【GitHub 】中已收录,里面包含不同方向的自学编程路线、面试题集合/面经、及系列技术文章等,资源持续更新中…

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值