BlockCanary
BlockCanary是国内开发者MarkZhai开发的一套性能监控组件,它对主线程操作进行了完全透明的监控,并能输出有效的信息,帮助开发分析、定位到问题所在,迅速优化应用。
主要特点:
- 非侵入式,简单的两行就打开监控,不需要到处打点,破坏代码优雅性。
- 精准,输出的信息可以帮助定位到问题所在(精确到行),不需要像Logcat一样,慢慢去找。
- 目前包括了核心监控输出文件,以及UI显示卡顿信息功能
使用
1、配置 build.gradle文件
// compile 'com.github.moduth:blockcanary-android:1.2.1'
// 仅在debug包启用BlockCanary进行卡顿监控和提示的话,可以这么用
debugCompile 'com.github.moduth:blockcanary-android:1.2.1'
// releaseCompile 'com.github.moduth:blockcanary-no-op:1.2.1'
2、新建一个类,继承自BlockCanaryContext,实现自己的监控上下文
public class AppBlockContext extends BlockCanaryContext {
private static final String TAG = AppBlockContext.class.getSimpleName();
private boolean DEBUG = true;
//设置卡顿阈值
@Override
public int getConfigBlockThreshold() {
return 500;
}
//是否显示卡顿信息
@Override
public boolean isNeedDisplay() {
return DEBUG;
}
//日志存放SD卡目录
@Override
public String getLogPath() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "blockcanary"+File.separator;
File file = new File(path);
if (!file.exists()){
file.mkdirs();
}
return file.getAbsolutePath();
}
}
(阈值大小可以自行设置,单位ms)
原理:主要利用了主线程的消息队列机制,通过Looper.getMainLooper().setMessageLogging(mainLooperPrinter);
通过mainLooperPrinter判断start和end,获取到dispatch消息的开始和结束时间,如果两个时间差超过阈值,就判定为主线程卡顿发生,dump出内存、cup等各项信息。
3、在Application的OnCreate()中初始化
public class BlockApplication extends Application {
public void onCreate() {
super.onCreate();
//初始化配置信息
BlockCanary.install(this, new AppBlockContext()).start();
}
}