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

相关推荐
私人珍藏库5 小时前
[Android] 会计快题库 -财会职称考试刷题学习
android·人工智能·学习·app·软件·多功能
安卓修改大师11 小时前
安卓修改大师 vs MT管理器:反编译工具终极对决与全景解析
android·人工智能·机器翻译
程序员小八77712 小时前
从 0 学习 MySQL 索引——7 大核心精讲
android·学习·mysql
雅客李13 小时前
2026云手机低价机型实测 安卓云手机踩坑测评报告
android·智能手机
蓝速科技14 小时前
蓝速科技鸿蒙广告机替代安卓实测:信创系统下的性能与边界评估
android·科技·harmonyos
雅客李14 小时前
2026云手机高负载压力测评 安卓云手机多开实测数据
android·智能手机·php
千里马学框架16 小时前
google官方Perfetto 中使用 AI相关skill
android·人工智能·ai·framework·perfetto·性能·skill
zhangphil17 小时前
Android RecyclerView图像类ViewHolder离屏缓存数量直接增加Java/View对象内存,间接增加Graphics/GL内存
android
众少成多积小致巨18 小时前
Android C++ 编码规范指南
android·c++·google
雅客李19 小时前
2026云手机旗舰机型评测 安卓云手机游戏帧率实测
android·智能手机