介绍 
BlockCanary是Android平台上的一个轻量的,非侵入式的性能监控组件,应用只需要提供一些上下文环境就可以在使用应用的时候检测主线程上的各种卡顿问题,并通过组件提供的各种信息分析出原因并进行修复。
BlockCanary会在发生卡顿的时候记录各种信息,输出到配置目录下的文件,并弹出消息栏通知。

核心原理介绍
关于UI的操作,都是通过唯一的Handler.MainLooper来分发实现的。整个应用的主线程,只有这一个looper,不管有多少handler,最后都会回到这里。而在Looper.loop()方法中,会在每次执行handle操作的时候,都调用logger进行打印操作,在执行Handler之前和之后,各打印一次。
public static void loop() {
    ...

    for (;;) {
        ...

        // This must be in a local variable, in case a UI event sets the logger
        Printer logging = me.mLogging;
        //执行Handler操作之前
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        //执行Handler操作时
        msg.target.dispatchMessage(msg);

        //执行Handler操作之后
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }

        ...
    }
}
因此,利用了主线程的消息队列处理机制,通过
Looper.getMainLooper().setMessageLogging(mainLooperPrinter);
并在mainLooperPrinter中判断start和end,来获取主线程dispatch该message的开始和结束时间,并判定该时间超过阈值(如2000毫秒)为主线程卡慢发生,并dump出各种信息,提供开发者分析性能瓶颈。

UML类图
Android-BlockCanary框架源码分析

参考
https://juejin.im/entry/5699f7dc60b2b80a9ea7db05
https://github.com/markzhai/AndroidPerformanceMonitor

相关文章:

  • 2021-09-06
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
  • 2021-12-16
猜你喜欢
  • 2022-02-18
  • 2021-08-10
  • 2021-07-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2021-07-01
相关资源
相似解决方案