检测Android UI卡顿的工具-BlockCanary

BlockCanary

BlockCanary是国内开发者MarkZhai开发的一套性能监控组件,它对主线程操作进行了完全透明的监控,并能输出有效的信息,帮助开发分析、定位到问题所在,迅速优化应用。

主要特点:

  1. 非侵入式,简单的两行就打开监控,不需要到处打点,破坏代码优雅性。
  2. 精准,输出的信息可以帮助定位到问题所在(精确到行),不需要像Logcat一样,慢慢去找。 
  3. 目前包括了核心监控输出文件,以及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();
    }
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值