Choreographer机制和卡顿优化,Android未来路在何方

notifyRendererOfFramePending();

pokeDrawLockIfNeeded();

}

}

而这个mTraversalRunnable就是我们所要执行的任务了,那究竟是何时执行呢?

首先会mChoreographer.postCallback会间接调用postCallbackDelayedInternal方法

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

if (dueTime <= now) {

scheduleFrameLocked(now);

} else {

Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_CALLBACK, action);

msg.arg1 = callbackType;

msg.setAsynchronous(true);

mHandler.sendMessageAtTime(msg, dueTime);

}

}

}

我们可以看到正常情况下会执行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.

if (isRunningOnLooperThreadLocked()) {

scheduleVsyncLocked();

} else {

Message msg = mHandler.obtainMessage(MSG_DO_SCHEDULE_VSYNC);

msg.setAsynchronous(true);

mHandler.sendMessageAtFrontOfQueue(msg);

}

} else {

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

}

}

}

由于在4.1上是使用VSYNC信号的,所以就自然会调用scheduleVsyncLocked方法,会间接调用scheduleVsync方法

**

  • Schedules a single vertical sync pulse to be delivered when the next

  • display frame begins.

*/

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

}

}

注意:这里的注释说的很清楚了,当下一帧来临时准备一个要分发的垂直同步信号,啥意思呢?简单来说就是当调用了nativeScheduleVsync方法时,当屏幕需要刷新的时候,也就是每隔16.6ms会通过native的looper分发到java层,从而调用java的方法,那是哪个方法呢?

// Called from native code.

@SuppressWarnings(“unused”)

private void dispatchVsync(long timestampNanos, int builtInDisplayId, int frame) {

onVsync(timestampNanos, builtInDisplayId, frame);

}

很明显是此方法

举个例子,比如屏幕显示的是第一帧,你在第一帧调用invalidate,其实并不是立即刷新的,而是在一帧会去注册一个Vsync(前提是这一帧cpu空闲情况下),当下一帧来临时也就是第二帧的时候会调用dispatchVsync此方法,当然这是一种比较简单的情况,复杂的等会说

那么来看一下调用的onVsync方法

public void onVsync(long timestampNanos, int builtInDisplayId, int frame) {

// Ignore vsync from secondary display.

// This can be problematic because the call to scheduleVsync() is a one-shot.

// We need to ensure that we will still receive the vsync from the primary

// display which is the one we really care about. Ideally we should schedule

// 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.");

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

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

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

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

学习分享

在当下这个信息共享的时代,很多资源都可以在网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2020最新上万页的大厂面试真题

七大模块学习资料:如NDK模块开发、Android框架体系架构…

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
第一,学习知识比较碎片化,没有合理的学习路线与进阶方向。
第二,开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
网络上找到,只取决于你愿不愿意找或是找的方法对不对了

很多朋友不是没有资料,大多都是有几十上百个G,但是杂乱无章,不知道怎么看从哪看起,甚至是看后就忘

如果大家觉得自己在网上找的资料非常杂乱、不成体系的话,我也分享一套给大家,比较系统,我平常自己也会经常研读。

2020最新上万页的大厂面试真题

[外链图片转存中…(img-UXM3f6kt-1711385592958)]

七大模块学习资料:如NDK模块开发、Android框架体系架构…

[外链图片转存中…(img-7eCehFyD-1711385592959)]

只有系统,有方向的学习,才能在段时间内迅速提高自己的技术。

这份体系学习笔记,适应人群:
第一,学习知识比较碎片化,没有合理的学习路线与进阶方向。
第二,开发几年,不知道如何进阶更进一步,比较迷茫。
第三,到了合适的年纪,后续不知道该如何发展,转型管理,还是加强技术研究。如果你有需要,我这里恰好有为什么,不来领取!说不定能改变你现在的状态呢!
由于文章内容比较多,篇幅不允许,部分未展示内容以截图方式展示 。如有需要获取完整的资料文档的朋友点击我的GitHub免费获取。

  • 7
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值