返回

监控主线程耗时操作,避免ANR,提升软件品质

Android

背景知识:

  • 主线程:Android系统中的主线程,负责处理UI事件和应用程序的逻辑处理。
  • ANR(Application Not Responding):当主线程响应用户操作延迟超过5秒时,系统会弹出一个“应用程序无响应”的提示框,即ANR。

解决方案:

  1. 定义一个打印函数
private static void printSlowOperationStack(long threshold) {
    Looper.getMainLooper().setMessageLogging(new MessageLoggingHandler(threshold) {
        @Override
        protected void printLog(Message message, long wallTime, long threadTime) {
            if (wallTime - message.getWhen() > threshold) {
                Log.w("SlowOperation", "Slow operation: " + wallTime + "ms, threadTime: " + threadTime + "ms, message: " + message);
            }
        }
    });
}
  1. 在合适的地方启动打印函数
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    printSlowOperationStack(1000);  //打印超过1秒的耗时操作
}

原理:

  • 将记录Message的日志功能添加到主线程的Looper中。
  • 覆写MessageLoggingHandler.printLog()方法,当Message的处理时间超过阈值时,打印耗时操作的信息,包括Message、耗时和线程时间。

优点:

  • 简单易用,只需要在主线程的Looper中添加一个打印耗时操作的函数即可。
  • 不影响应用程序的性能,因为只有当耗时操作超过阈值时才会打印日志。
  • 可以快速定位主线程中的耗时操作,并及时采取措施进行优化。

注意:

  • 阈值的设定要根据应用程序的具体情况而定,太小可能会打印太多无用的日志,太大会漏掉一些重要的耗时操作。
  • 这种方法只能监控主线程中的耗时操作,无法监控其他线程中的耗时操作。