Choreographer机制和卡顿优化,2021Android大厂面试题来袭

本文详细解析了Android的Choreographer机制,包括如何调度UI更新以确保流畅性,以及如何处理帧丢失和卡顿。Choreographer通过监听vsync信号并调度消息来确保帧间的同步。当应用主线程工作负载过大导致帧率下降时,Choreographer会记录Skipped frames,但这并不直接意味着UI卡顿。文章还探讨了卡顿优化的两种方案,包括分析Looper的日志和使用Choreographer.FrameCallback。
摘要由CSDN通过智能技术生成
  • "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 (skipped

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值