[关闭]
@TryLoveCatch 2022-05-18T11:44:39.000000Z 字数 6868 阅读 1078

Android知识体系之异常处理-卡顿

Android知识体系


参考

自动化卡顿检测方案及优化
深入探索Android卡顿优化(上)
深入探索Android卡顿优化(下)

卡顿

关于什么是卡顿?可以参考什么是卡顿

原理

一个线程不管有多少Handler,它只会有一个Looper存在,主线程执行的任何代码都会通过Looper.loop()方法执行。而在Looper函数中,它有一个mLogging对象,这个对象在每个message处理前后都会被调用。主线程发生了卡顿,那一定是在dispatchMessage()方法中执行了耗时操作。那么,我们就可以通过这个mLogging对象对dispatchMessage()进行监控。

在线监测

利用loop()中打印的日志

大家都知道在Android UI线程中有个Looper,在其loop方法中会不断取出Message,调用其绑定的Handler在UI线程进行执行。

大致代码如下:

  1. public static void loop() {
  2. final Looper me = myLooper();
  3. final MessageQueue queue = me.mQueue;
  4. // ...
  5. for (;;) {
  6. Message msg = queue.next(); // might block
  7. // This must be in a local variable, in case a UI event sets the logger
  8. Printer logging = me.mLogging;
  9. if (logging != null) {
  10. logging.println(">>>>> Dispatching to " + msg.target + " " +
  11. msg.callback + ": " + msg.what);
  12. }
  13. // focus
  14. msg.target.dispatchMessage(msg);
  15. if (logging != null) {
  16. logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
  17. }
  18. // ...
  19. }
  20. msg.recycleUnchecked();
  21. }
  22. }

第15行代码,就是有可能发生卡顿的地方,注意这行代码的前后,有两个logging。如果设置了logging,会分别打印出“>>>>> Dispatching to”和“<<<<< Finished to”这样的Log。这样就给我们监视两次Log之间的时间差,来判断是否发生了卡顿。

  1. public final class Looper {
  2. private Printer mLogging;
  3. public void setMessageLogging(@Nullable Printer printer) {
  4. mLogging = printer;
  5. }
  6. }
  7. public interface Printer {
  8. void println(String x);
  9. }

所以,我们可以自己实现一个Printer,在通过setMessageLogging()方法传入即可。

  1. public class MyApplication extends Application {
  2. @Override
  3. public void onCreate() {
  4. super.onCreate();
  5. Looper.getMainLooper().setMessageLogging(new Printer() {
  6. private static final String START = ">>>>> Dispatching";
  7. private static final String END = "<<<<< Finished";
  8. @Override
  9. public void println(String x) {
  10. if (x.startsWith(START)) {
  11. LogMonitor.getInstance().startMonitor();
  12. }
  13. if (x.startsWith(END)) {
  14. LogMonitor.getInstance().removeMonitor();
  15. }
  16. }
  17. });
  18. }
  19. }

LogMonitor的代码如下:

  1. public class LogMonitor {
  2. private static final long TIME_BLOCK = 1000L;
  3. private static LogMonitor sInstance = new LogMonitor();
  4. private HandlerThread mHandlerThread = new HandlerThread("log");
  5. private Handler mHandler;
  6. private LogMonitor() {
  7. mHandlerThread.start();
  8. mHandler = new Handler(mHandlerThread.getLooper());
  9. }
  10. private static Runnable mRunnable = new Runnable() {
  11. @Override
  12. public void run() {
  13. StringBuilder sb = new StringBuilder();
  14. StackTraceElement[] stackTrace = Looper.getMainLooper().getThread().getStackTrace();
  15. for (StackTraceElement s : stackTrace) {
  16. sb.append(s.toString() + "\n");
  17. }
  18. Log.e("TAG", sb.toString());
  19. }
  20. };
  21. public static LogMonitor getInstance() {
  22. return sInstance;
  23. }
  24. public void startMonitor() {
  25. mHandler.postDelayed(mRunnable, TIME_BLOCK);
  26. }
  27. public boolean isMonitor() {
  28. return mHandler.hasCallbacks(mRunnable);
  29. }
  30. public void removeMonitor() {
  31. mHandler.removeCallbacks(mRunnable);
  32. }
  33. }

我们假设阀值是1000ms,也就是说超过1000ms的都算卡顿。
当“>>>>> Dispatching to”打印了,我们就发送一个延迟1秒钟的任务,这个任务会打印出造成卡顿的UI线程里的堆栈信息。
如果在1秒钟之内我们检测到了“<<<<< Finished to”打印,就会移除这个延迟1秒的任务。
如果1秒内没有检测到“<<<<< Finished to”打印,

BlockCanary就是基于这个原理实现的。

利用Choreographer

Android性能优化第(十 一)篇---卡顿分析,正确评测流畅度

Choreographer就是一个消息处理器,根据vsync 信号 来计算frame,而计算frame的方式就是处理三种回调,包括事件回调、动画回调、绘制回调。这三种事件在消息输入、加入动画、准备绘图layout 等动作时均会发给Choreographer。

有的时候会看到这样的log,系统帮助我们打印出了跳帧数:

  1. 02-07 19:47:04.333 17601-17604/zhangwan.wj.com.choreographertest D/dalvikvm: GC_CONCURRENT freed 143K, 3% free 9105K/9384K, paused 2ms+0ms, total 6ms
  2. 02-07 19:47:04.337 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 60 frames! The application may be doing too much work on its main thread.
  3. 02-07 19:47:11.685 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 85 frames! The application may be doing too much work on its main thread.
  4. 02-07 19:47:12.545 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
  5. 02-07 19:47:14.893 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
  6. 02-07 19:47:23.049 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
  7. 02-07 19:47:23.929 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 37 frames! The application may be doing too much work on its main thread.
  8. 02-07 19:47:24.961 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 61 frames! The application may be doing too much work on its main thread.
  9. 02-07 19:47:25.817 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.
  10. 02-07 19:47:26.433 17601-17601/zhangwan.wj.com.choreographertest I/Choreographer: Skipped 36 frames! The application may be doing too much work on its main thread.

这个log就出自于Choreographer中

  1. public final class Choreographer {
  2. void doFrame(long frameTimeNanos, int frame) {
  3. final long startNanos;
  4. synchronized (mLock) {
  5. if (!mFrameScheduled) {
  6. return; // no work to do
  7. }
  8. //当前时间
  9. startNanos = System.nanoTime();
  10. //抖动间隔
  11. final long jitterNanos = startNanos - frameTimeNanos;
  12. //抖动间隔大于屏幕刷新时间间隔(16ms)
  13. if (jitterNanos >= mFrameIntervalNanos) {
  14. final long skippedFrames = jitterNanos / mFrameIntervalNanos;
  15. //跳过了几帧!,也许当前应用在主线程做了太多的事情。
  16. if (skippedFrames >= SKIPPED_FRAME_WARNING_LIMIT) {
  17. Log.i(TAG, "Skipped " + skippedFrames + " frames! "
  18. + "The application may be doing too much work on its main thread.");
  19. }
  20. //最后一次的屏幕刷是lastFrameOffset之前开始的
  21. final long lastFrameOffset = jitterNanos % mFrameIntervalNanos;
  22. if (DEBUG) {
  23. Log.d(TAG, "Missed vsync by " + (jitterNanos * 0.000001f) + " ms "
  24. + "which is more than the frame interval of "
  25. + (mFrameIntervalNanos * 0.000001f) + " ms! "
  26. + "Skipping " + skippedFrames + " frames and setting frame "
  27. + "time to " + (lastFrameOffset * 0.000001f) + " ms in the past.");
  28. }
  29. //最后一帧的刷新开始时间
  30. frameTimeNanos = startNanos - lastFrameOffset;
  31. }
  32. //由于跳帧可能造成了当前展现的是之前的帧,这样需要等待下一个vsync信号
  33. if (frameTimeNanos < mLastFrameTimeNanos) {
  34. if (DEBUG) {
  35. Log.d(TAG, "Frame time appears to be going backwards. May be due to a "
  36. + "previously skipped frame. Waiting for next vsync.");
  37. }
  38. scheduleVsyncLocked();
  39. return;
  40. }
  41. //当前画面刷新的状态置false
  42. mFrameScheduled = false;
  43. //更新最后一帧的刷新时间
  44. mLastFrameTimeNanos = frameTimeNanos;
  45. }
  46. //按照优先级策略进行画面刷新时间处理
  47. doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos);
  48. doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos);
  49. doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
  50. if (DEBUG) {
  51. final long endNanos = System.nanoTime();
  52. Log.d(TAG, "Frame " + frame + ": Finished, took "
  53. + (endNanos - startNanos) * 0.000001f + " ms, latency "
  54. + (startNanos - frameTimeNanos) * 0.000001f + " ms.");
  55. }
  56. }
  57. }

当跳帧数大于设置的SKIPPED_FRAME_WARNING_LIMIT 值时会在当前进程输出这个log。由于 SKIPPED_FRAME_WARNING_LIMIT 的值默认为 30,所以上面的log并不是经常看到。

方法一

如果我们用反射的方法把SKIPPED_FRAME_WARNING_LIMIT的值设置成1,这样可以保证只要有丢帧,就会有上面的log输出来。

  1. static {
  2. try {
  3. Field field = Choreographer.class.getDeclaredField("SKIPPED_FRAME_WARNING_LIMIT");
  4. field.setAccessible(true);
  5. field.set(Choreographer.class, 1);
  6. } catch (Throwable e) {
  7. e.printStackTrace();
  8. }
  9. }

只要捕获这个log提取出skippedFrames 就可以知道界面是否卡顿。

方法二

上面的方法只能让我们知道丢帧了,却无法知道更详细定位问题的信息了。
在Choreographer中有个回调接口,FrameCallback。

  1. public interface FrameCallback {
  2. //当新的一帧被绘制的时候被调用。
  3. public void doFrame(long frameTimeNanos);
  4. }
  1. public class BlockDetectByChoreographer {
  2. public static void start() {
  3. Choreographer.getInstance()
  4. .postFrameCallback(new Choreographer.FrameCallback() {
  5. @Override
  6. public void doFrame(long l) {
  7. if (LogMonitor.getInstance().isMonitor()) {
  8. LogMonitor.getInstance().removeMonitor();
  9. }
  10. LogMonitor.getInstance().startMonitor();
  11. Choreographer.getInstance().postFrameCallback(this);
  12. }
  13. });
  14. }
  15. }

第一次的时候开始检测,如果大于阈值则输出相关堆栈信息,否则则移除。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注