Android卡顿优化 | 自动化卡顿检测方案与优化(AndroidPerformanceMonitor / BlockCanary)

本文要点

  • 为何需要自动化检测方案
  • 自动卡顿检测方案原理
  • 看一下Looper.loop()源码
  • 实现思路
  • AndroidPerformanceMonitor实战
  • 基于AndroidPerformanceMonitor源码简析
  • 接下来我们讨论一下方案的不足
  • 自动检测方案优化
项目GitHub

为何需要自动化检测方案

  • 前面提到过的系统工具只适合线下针对性分析,无法带到线上!
  • 线上及测试环节需要自动化检测方案

方案原理

  • 源于Android的消息处理机制;
    一个线程不管有多少Handler,只会有一个Looper存在,
    主线程中所有的代码,都会通过Looper.loop()执行;
  • loop()中有一个mLogging对象,
    它在每个Message处理前后都会被调用:
    9125154-93970f5affdc46bc.png
  • 如果主线程发生卡顿,
    一定是在dispatchMessage执行了耗时操作!
    9125154-63b635b59a1a1434.png
    Handler机制图

由此,我们便可以通过mLogging对象
dispatchMessage执行的时间进行监控;

看一下Looper.loop()源码

    public static void loop() {
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        final MessageQueue queue = me.mQueue;

        // Make sure the identity of this thread is that of the local process,
        // and keep track of what that identity token actually is.
        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

        for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

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

            final long traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresho
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌川江雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值