Looper机制监测卡顿

Android性能监测:Looper机制监测卡顿

一.简介

​ 要使用Looper机制检测卡顿,建议先熟悉一下Looper机制。

​ 要是了解Looper机制,那么对于理解基于Looper机制监测卡顿的原理就会十分的简单。它对卡顿的检测的步骤大致可分为三步:

1.在Looper对消息处理的循环里,每当取出一个消息,先记录下时间开始t1。

2.然后当Looper里面处理完这个消息后记录记录一下结束时间t2。

3.用结束时间 t2 减去开始时间 t1 ,他们的差值就是处理这个消息所花费的时间,当他们的差值大于某一个我们设定的阈值后,就认为发生了卡顿,然后把相关的信息打印出来。

二.代码分析

​ 上面我们了解了它的基本原理那么我们怎么实现它呢?,幸运的是Android 的Loopr机制里面已经给我们埋好了伏笔

就如下面代码所描述的就是我们上面总结的原理,同时我么那还可以注意到:在注释2 处 在处理消息之前 , 会先判断 logging != null 然后用 打印出一些信息,然后在处理完消息后 也会有类似的操作, 还可以注意到在注释1 处有这样的代码 final Printer logging = me.mLogging; ,到这里已经很明了了,Looper里面已经预留了我们监测Looper的伏笔: 我么你只需要自己实现一个logging(Printer类),然后把它设置给Looper,这样就可以检测Looper了。

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;
    
    ....
    
      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;  // 注释1  这里把logging设置给了Looper
          	// 在处理一个消息之前记录下时间 
            if (logging != null) {
    
       // 注释2 
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }
            
            
          	// 中间省略处理消息的过程
          
            
          
         	// 消息处理结束后再记录下时间
            if (logging != null) {
    
    
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }
            
         ....
         }

​ 只要检测 msg.target.dispatchMessage(msg) 的执行时间,就能检测到部分UI线程是否有耗时的操作。注意到这行执行代码的前后,有两个logging.println函数,如果设置了logging,会分别打印出**>>>>> Dispatching to<<<<< Finished to** 这样的日志,这样我们就可以通过两次log的时间差值,来计算dispatchMessage的执行时间,从而设置阈值判断是否发生了卡顿。

三.代码实现

​ 直接看看带佬怎么写的,我就不献丑了
Android性能监测:Looper机制监测卡顿和丢帧(二)

猜你喜欢

转载自blog.csdn.net/qq_41095045/article/details/123909927