简单易用的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

相关推荐
Onion_9919 分钟前
学习下Github上的Android CICD吧
android·github
来来走走1 小时前
Flutter Form组件的基本使用
android·flutter
顾林海1 小时前
Android MMKV 深度解析:原理、实践与源码剖析
android·面试·源码阅读
雨白2 小时前
TCP/IP 核心概念详解:从网络分层到连接管理
android
Wgllss3 小时前
雷电雨效果:Kotlin+Compose+协程+Flow 实现天气UI
android·架构·android jetpack
用户207038619495 小时前
Compose 可点击文本:ClickableText Compose 中的 ClickableSpan
android
常利兵5 小时前
Kotlin作用域函数全解:run/with/apply/let/also与this/it的魔法对决
android·开发语言·kotlin
幼稚园的山代王5 小时前
Kotlin-基础语法练习一
android·开发语言·kotlin
闻不多5 小时前
用llamaindex搭建GAR遇到400
android·运维·服务器
阿华的代码王国5 小时前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互