Android-BlockCanary框架源码分析
介绍
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类图
参考
https://juejin.im/entry/5699f7dc60b2b80a9ea7db05
https://github.com/markzhai/AndroidPerformanceMonitor
还没有评论,来说两句吧...