2.16 BlockCanary实现原理

less than 1 minute read

2.13.1 BlockCanary

  • Looper#loop(), 主线程分发处理消息, 前后都会打印日志
for (;;) {
           // 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);
           }
           // 主线程分发处理消息
           msg.target.dispatchMessage(msg);
           if (logging != null) {
               logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
           }
       }
  • Looper#setMessageLogging设置日志打印器, 并在Printer#logging监听, 即LooperMonitor#isBlock(), 当endTime - mStartTimestamp大于mBlockThresholMillis(默认是3秒), 则发送BlockEvent, 采集相关堆栈
  • StackSampler, CpuSampler, 堆栈和Cpu采集, Cpu通过读取/proc/pid/stat读取niceuseriowait等信息

参考