• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

BlockCanary源码解析

android 搞代码 3年前 (2022-05-09) 21次浏览 已收录 0个评论

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的流程图在下面也呈现了。所以这篇博客也就写道这里吧。心愿对大家,对于卡顿的了解有肯定的帮忙。


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:BlockCanary源码解析

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址