关于android:BlockCanary源码解析

2次阅读

共计 8678 个字符,预计需要花费 22 分钟才能阅读完成。

BlockCanary 源码解析

在解说 BlockCanary 源码之前,咱们还是须要将一些前置的知识点。本文不讲 Handler 的原理了,不太懂的同学本人去百度看一下吧。

什么是卡顿

在解说卡顿问题之前,咱们须要讲一下 帧率 这个概念。帧率是以帧称为单位的位图图像间断呈现在显示器上的频率。我将一个例子,电影播放。电影其实就是很多张照片(帧)的一个汇合,那为什么看起来是一个间断的过程呢?因为电影每一秒呈现过的图片不止一张。实际上电影个别一秒呈现的图片张数会在 20-30 张。假如电影一秒呈现了 24 张图片,那么这个电影的帧率就是 24。帧率就是一秒中,呈现了多少帧。

晓得了什么是帧率,那么问题来了,为什么会呈现卡顿呢?卡顿在咱们的视觉下面的体现就是本来是晦涩的动画画面,当初变的不晦涩了。咱们下面讲过,动画其实是由很多图片形成。如果在一个 24 帧的电影中,忽然有一秒钟,在这一秒钟呈现了掉帧。也就是本来 0 …23 的图片变成了 0…10…12…23. 两头的某一帧没有渲染进去,那么这个在咱们视觉上就会呈现不晦涩的景象。也就是卡顿的景象。下面就是电影上呈现卡顿的景象。那么在咱们 android 零碎上呢?

Android 渲染机制

在高刷手机没有呈现之前,咱们手机屏幕的帧率是 60。就是意味着 1 秒钟会有 60 个画面呈现。那么也就是 16ms 就要有一个画面渲染。**Android 零碎每隔 16ms 收回 VSYNC 信号,触发对 UI 进行渲染,如果每次渲染都胜利,这样就可能达到晦涩的画面所须要的 60 帧,为了可能实现 60fps,这意味着程序的大多数操作都必须在 16ms 内实现。如果超过了 16ms 那么可能就呈现丢帧的状况。** 如果掉帧的频率很高,也就是导致卡顿的状况。

BlockCanary 源码解析

那么在 android 中,BlockCanary是怎么帮忙咱们去做卡顿检测的呢。明天咱们就来解说一下 BlockCanary 检测卡顿的原理。

个别咱们都通过以下的代码形式去开启咱们的卡顿检测。

public class DemoApplication extends Application {
    @Override
    public void onCreate() {
        // ...
        // Do it on main process
        BlockCanary.install(this, new AppBlockCanaryContext()).start();}
}

这段代码次要有两局部,一部分是 install,一部分是 start。咱们先看 install 局部

install 阶段
BlockCanary#install()
public static BlockCanary install(Context context, BlockCanaryContext blockCanaryContext) {
    //BlockCanaryContext.init 会将保留利用的 applicationContext 和用户设置的配置参数
        BlockCanaryContext.init(context, blockCanaryContext);
    //etEnabled 将依据用户的告诉栏音讯配置开启
        setEnabled(context, DisplayActivity.class, BlockCanaryContext.get().displayNotification());
        return get();}

BlockCanary#get()
// 应用单例创立了一个 BlockCanary 对象    
public static BlockCanary get() {if (sInstance == null) {synchronized (BlockCanary.class) {if (sInstance == null) {sInstance = new BlockCanary();
            }
        }
    }
    return sInstance;
}
BlockCanary()
  private BlockCanary() {
      // 初始化 blockCanaryInternals 调度类
      BlockCanaryInternals.setContext(BlockCanaryContext.get());
      mBlockCanaryCore = BlockCanaryInternals.getInstance();
      // 为 BlockCanaryInternals 增加拦截器(责任链)BlockCanaryContext 对 BlockInterceptor 是空实现
      mBlockCanaryCore.addBlockInterceptor(BlockCanaryContext.get());
      if (!BlockCanaryContext.get().displayNotification()) {return;}
      //DisplayService 只在开启告诉栏音讯的时候增加,当卡顿产生时将通过 DisplayService 发动告诉栏音讯
      mBlockCanaryCore.addBlockInterceptor(new DisplayService());

  }
BlockCanaryInternals.getInstance()
static BlockCanaryInternals getInstance() {if (sInstance == null) {synchronized (BlockCanaryInternals.class) {if (sInstance == null) {sInstance = new BlockCanaryInternals();
            }
        }
    }
    return sInstance;
}
BlockCanaryInternals
public BlockCanaryInternals() {
        // 初始化栈采集器
        stackSampler = new StackSampler(Looper.getMainLooper().getThread(),
                sContext.provideDumpInterval());
        // 初始化 cpu 采集器
        cpuSampler = new CpuSampler(sContext.provideDumpInterval());

        // 初始化 LooperMonitor,并实现了 onBlockEvent 的回调,该回调会在触发阈值后被调用, 这外面比拟重要
        setMonitor(new LooperMonitor(new LooperMonitor.BlockListener() {

            @Override
            public void onBlockEvent(long realTimeStart, long realTimeEnd,
                                     long threadTimeStart, long threadTimeEnd) {
                ArrayList<String> threadStackEntries = stackSampler
                        .getThreadStackEntries(realTimeStart, realTimeEnd);
                if (!threadStackEntries.isEmpty()) {BlockInfo blockInfo = BlockInfo.newInstance()
                            .setMainThreadTimeCost(realTimeStart, realTimeEnd, threadTimeStart, threadTimeEnd)
                            .setCpuBusyFlag(cpuSampler.isCpuBusy(realTimeStart, realTimeEnd))
                            .setRecentCpuRate(cpuSampler.getCpuRateInfo())
                            .setThreadStackEntries(threadStackEntries)
                            .flushString();
                    LogWriter.save(blockInfo.toString());

                    if (mInterceptorChain.size() != 0) {for (BlockInterceptor interceptor : mInterceptorChain) {interceptor.onBlock(getContext().provideContext(), blockInfo);
                        }
                    }
                }
            }
        }, getContext().provideBlockThreshold(), getContext().stopWhenDebugging()));

        LogWriter.cleanObsolete();}

当 install 进行初始化实现后,接着会调用 start()办法,实现如下:

start 阶段
BlockCanary#start()
//BlockCanary#start()
public void start() {if (!mMonitorStarted) {
        mMonitorStarted = true;
        // 把 mBlockCanaryCore 中的 monitor 设置 MainLooper 中进行监听
        Looper.getMainLooper().setMessageLogging(mBlockCanaryCore.monitor);
    }
}

这外面的实现也比较简单,就是获取到主线程 Looper 而后将上一步创立的 LooperMonitor 设置到主线程 Looper 外面的 MessageLogging。

到这里而后呢?卧槽,没了一开始看这里的源码的时候我也是很懵逼的。而后我就去 github 上看了,而后呢,我看到了这么一张图。

通过这张图,我能够晓得,真正开始检测的不是 start(),而是 Looper 外面 loop()函数

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.");
    }
    if (me.mInLoop) {
        Slog.w(TAG, "Loop again would have the queued messages be executed"
               + "before this one completed.");
    }

    me.mInLoop = true;
    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);
        }
        // Make sure the observer won't change while processing a transaction.
        final Observer observer = sObserver;

        final long traceTag = me.mTraceTag;
        long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
        long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
        if (thresholdOverride > 0) {
            slowDispatchThresholdMs = thresholdOverride;
            slowDeliveryThresholdMs = thresholdOverride;
        }
        final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
        final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

        final boolean needStartTime = logSlowDelivery || logSlowDispatch;
        final boolean needEndTime = logSlowDispatch;

        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }

        final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
        final long dispatchEnd;
        Object token = null;
        if (observer != null) {token = observer.messageDispatchStarting();
        }
        long origWorkSource = ThreadLocalWorkSource.setUid(msg.workSourceUid);
        try {msg.target.dispatchMessage(msg);
            if (observer != null) {observer.messageDispatched(token, msg);
            }
            dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;} catch (Exception exception) {if (observer != null) {observer.dispatchingThrewException(token, msg, exception);
            }
            throw exception;
        } finally {ThreadLocalWorkSource.restore(origWorkSource);
            if (traceTag != 0) {Trace.traceEnd(traceTag);
            }
        }
        if (logSlowDelivery) {if (slowDeliveryDetected) {if ((dispatchStart - msg.when) <= 10) {Slog.w(TAG, "Drained");
                    slowDeliveryDetected = false;
                }
            } else {
                if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                                msg)) {
                    // Once we write a slow delivery log, suppress until the queue drains.
                    slowDeliveryDetected = true;
                }
            }
        }
        if (logSlowDispatch) {showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", msg);
        }

        if (logging != null) {logging.println("<<<<< Finished to" + msg.target + " " + msg.callback);
        }

        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + "to 0x"
                    + Long.toHexString(newIdent) + "while dispatching to"
                    + msg.target.getClass().getName() + " "
                    + msg.callback + "what=" + msg.what);
        }

        msg.recycleUnchecked();}
}

loop()外面的代码很长,咱们解说 blockCanary 的时候不须要过分关注其余局部,还记得咱们 start 做的事件吗,咱们去设置了 setMessageLogging。所以先看看setMessageLogging 办法

Looper#setMessageLogging
public void setMessageLogging(@Nullable Printer printer) {mLogging = printer;}

其实就是将创立的 LooperMonitor 赋值给 mLogging,那么咱们只须要关注 mLogging 在 loop()中的代码就好了。咱们发现就是调用了两次 println。一个是在 msg.target.dispatchMessage(msg) 之前,一个是在 msg.target.dispatchMessage(msg) 之后。也就是说这两次调用,一次是解决信号之前,一个是解决信号之后。那么通过实现 LooperMonitor 外面的 println 办法,咱们就能够得出一些时间差。所以,接下来咱们要看的是 LooperMonitor 外面的 println 办法

MainLooper#println()
//MainLooper#println()
@Override
public void println(String x) {
    // 如果再 debug 模式,不执行监听
    if (mStopWhenDebugging && Debug.isDebuggerConnected()) {return;}
    if (!mPrintingStarted) {  //dispatchMesage 前执行的 println
        // 记录开始工夫
        mStartTimestamp = System.currentTimeMillis();
        mStartThreadTimestamp = SystemClock.currentThreadTimeMillis();
        mPrintingStarted = true;
        // 开始采集栈及 cpu 信息
        startDump();} else {  //dispatchMesage 后执行的 println
        // 获取完结工夫
        final long endTime = System.currentTimeMillis();
        mPrintingStarted = false;
        // 判断耗时是否超过阈值
        if (isBlock(endTime)) {notifyBlockEvent(endTime);
        }
        stopDump();}
}

// 判断是否超过阈值
 private boolean isBlock(long endTime) {return endTime - mStartTimestamp > mBlockThresholdMillis;// 这个阈值是咱们本人设置的}

// 如果超过阈值,回调卡顿的监听,阐明卡顿了
private void notifyBlockEvent(final long endTime) {
    final long startTime = mStartTimestamp;
    final long startThreadTime = mStartThreadTimestamp;
    final long endThreadTime = SystemClock.currentThreadTimeMillis();
    HandlerThreadFactory.getWriteLogThreadHandler().post(new Runnable() {
        @Override
        public void run() {mBlockListener.onBlockEvent(startTime, endTime, startThreadTime, endThreadTime);
        }
    });
}

其实这里卡顿检测的源码也还是比较简单的,它的原理就是通过从新实现 looper 外面的 logging,而后通过 println 函数去判断有没有呈现卡顿。BlockCanary 的流程图在下面也呈现了。所以这篇博客也就写道这里吧。心愿对大家,对于卡顿的了解有肯定的帮忙。

正文完
 0