简单易用的Android主线程耗时检测类 MainThreadMonitor

适用场景 debug 本地测试

文章目录

  • [代码类 MainThreadMonitor.java](#代码类 MainThreadMonitor.java)
  • [使用方式 Application的attachBaseContext](#使用方式 Application的attachBaseContext)
  • log输出示例

代码类 MainThreadMonitor.java

java 复制代码
public class MainThreadMonitor {
    private static final String TAG = "MainThreadMonitor";
    private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);

    public static void startMonitorMainThread(long threshold) {
        executorService.scheduleAtFixedRate(() -> {
            checkMainThreadState(threshold);
        }, 0, threshold, TimeUnit.MILLISECONDS);
    }


    private static void checkMainThreadState(long threshold) {
        AtomicBoolean exec = new AtomicBoolean(false);
        long startTime = System.currentTimeMillis();

        Handler mainHandler = new Handler(Looper.getMainLooper());
        // 预期主线程执行runnable的时候会把 exec置为true
        mainHandler.post(() -> exec.set(true));

        executorService.schedule(() -> {
            // 阈值之后发现 exec 还没有置为true,说明主线程阻塞了
            if (!exec.get()) {
                printMainThreadStackTrace(startTime);
            }
        }, threshold, TimeUnit.MILLISECONDS);
    }

    private static void printMainThreadStackTrace(long startTime) {
        StackTraceElement[] stackTrace = Looper.getMainLooper().getThread().getStackTrace();
        long consumeTime = System.currentTimeMillis() - startTime;
        Log.e(TAG, String.format("start block:(%s) ms  ====================== ", consumeTime));
        for (StackTraceElement s : stackTrace) {
            Log.d(TAG, "block: " + s);
        }
    }

}

使用方式 Application的attachBaseContext

kotlin 复制代码
class App : Application() {

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MainThreadMonitor.startMonitorMainThread(500)
    }

}

log输出示例

这里需要解释一下 start block 这行的含义,我们看到后面有一个 501ms的耗时,这里并不意味 着该方法/函数执行的时间是501ms,而是表述这500ms之内都在此方法中执行,很有可能下一个500ms还是这个堆栈信息,因此 方法实际执行时间 >= 500ms

相关推荐
xiangpanf7 小时前
Laravel 10.x重磅升级:五大核心特性解析
android
robotx10 小时前
安卓线程相关
android
消失的旧时光-194310 小时前
Android 面试高频:JSON 文件、大数据存储与断电安全(从原理到工程实践)
android·面试·json
dalancon11 小时前
VSYNC 信号流程分析 (Android 14)
android
dalancon12 小时前
VSYNC 信号完整流程2
android
dalancon12 小时前
SurfaceFlinger 上帧后 releaseBuffer 完整流程分析
android
用户693717500138413 小时前
不卷AI速度,我卷自己的从容——北京程序员手记
android·前端·人工智能
程序员Android13 小时前
Android 刷新一帧流程trace拆解
android
墨狂之逸才14 小时前
解决 Android/Gradle 编译报错:Comparison method violates its general contract!
android
阿明的小蝴蝶14 小时前
记一次Gradle环境的编译问题与解决
android·前端·gradle