BlockCanary是一套性能监控组件,监控Handler中的dispatchMessage过程所消耗的时间是否超过阀值来判断是否发生卡顿。
Looper#loop中有代码:
public static void loop() {
...
for (;;) {
...
//默认为null,可通过setMessageLogging()方法来指定输出,用于debug功能
Printer logging = me.mLogging;
if (logging != null) {
//事件分发之前的时间T1
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}
msg.target.dispatchMessage(msg);
if (logging != null) {
//事件分发之后的时间T2
logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
}
...
}
}
如果T2-T1的时间差大于某个阀值,就可以判断发生了卡顿,在BlockCanary中,阀值是3000ms。超过阀值之后,BlockCanary就会将一些必要的log日志输出.输出的展现方法类似leakCanary
基本使用:
引用:
dependencies {
compile 'com.github.markzhai:blockcanary-android:1.5.0'
// 仅在debug包启用BlockCanary进行卡顿监控和提示的话,可以这么用
debugCompile 'com.github.markzhai:blockcanary-android:1.5.0'
releaseCompile 'com.github.markzhai:blockcanary-no-op:1.5.0'
}
初始化
public class DemoApplication extends Application {
private static Context sContext;
@Override
public void onCreate() {
super.onCreate();
sContext = this;
BlockCanary.install(this, new AppContext()).start();
}
public static Context getAppContext() {
return sContext;
}
}
初始化过程实际上做了两件事情,install和start
public static BlockCanary install(Context context, BlockCanaryContext blockCanaryContext) {
//这里保存applicationContext和用户设置的参数
//其中所有的配置参数都可以自定义BlockCanaryContext的子类来实现
BlockCanaryContext.init(context, blockCanaryContext);
//开启或者关闭DisplayActivity视图以账号堆栈信息,这里会单开一个io信息来存储堆栈日志