原创|教你一分钟之内定位App冷启动卡顿

简介: 原创|教你一分钟之内定位App冷启动卡顿

前言


Tencent Matrix默认无法监测Application冷启动的耗时方法,本文介绍了如何改造Matrix支持冷启动耗时方法监测。让你一分钟就能给App启动卡顿号脉。

1. 接入Tencent Matrix


1.1 在你项目根目录下的 gradle.properties 中配置要依赖的 Matrix 版本号,如:

MATRIX_VERSION=1.0.0

1.2 在你项目根目录下的 build.gradle 文件添加 Matrix 依赖,如:


dependencies {
      classpath ("com.tencent.matrix:matrix-gradle-plugin:${MATRIX_VERSION}") { changing = true }
  }

1.3 在 app/build.gradle 文件中添加 Matrix 各模块的依赖,如:


  dependencies {
    implementation group: "com.tencent.matrix", name: "matrix-android-lib", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-android-commons", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-trace-canary", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-resource-canary-android", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-resource-canary-common", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-io-canary", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-sqlite-lint-android-sdk", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-battery-canary", version: MATRIX_VERSION, changing: true
    implementation group: "com.tencent.matrix", name: "matrix-hooks", version: MATRIX_VERSION, changing: true
  }
  apply plugin: 'com.tencent.matrix-plugin'
  matrix {
    trace {
        enable = true //if you don't want to use trace canary, set false
        baseMethodMapFile = "${project.buildDir}/matrix_output/Debug.methodmap"
        blackListFile = "${project.projectDir}/matrixTrace/blackMethodList.txt"
    }
  }

1.4 实现 PluginListener,接收 Matrix 处理后的数据, 如:

class MatrixListener(context: Context?) : DefaultPluginListener(context) {
    companion object {
        const val TAG: String = "Matrix.TestPluginListener"
    }
    override fun onReportIssue(issue: Issue) {
        super.onReportIssue(issue)
        MatrixLog.e(TAG, issue.toString())
    }
}

1.5 实现动态配置接口, 可修改 Matrix 内部参数. 在 sample-android 中 我们有个简单的动态接口实例DynamicConfigImplDemo.java, 其中参数对应的 key 位于文件 MatrixEnum中, 摘抄部分示例如下:

class MatrixConfig : IDynamicConfig {
    val isFPSEnable: Boolean
        get() = true
    val isTraceEnable: Boolean
        get() = true
    val isMatrixEnable: Boolean
        get() = true
    override fun get(key: String, defStr: String): String {
        // for Activity leak detect
        if (ExptEnum.clicfg_matrix_resource_detect_interval_millis.name == key || ExptEnum.clicfg_matrix_resource_detect_interval_millis_bg.name == key) {
            Log.d(
                "DynamicConfig",
                "Matrix.ActivityRefWatcher: clicfg_matrix_resource_detect_interval_millis 10s"
            )
            return TimeUnit.SECONDS.toMillis(5).toString()
        }
        if (ExptEnum.clicfg_matrix_resource_max_detect_times.name == key) {
            Log.d(
                "DynamicConfig",
                "Matrix.ActivityRefWatcher: clicfg_matrix_resource_max_detect_times 5"
            )
            return 3.toString()
        }
        return defStr
    }
    override fun get(key: String, defInt: Int): Int {
        //TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
        if (MatrixEnum.clicfg_matrix_resource_max_detect_times.name == key) {
            MatrixLog.i(TAG, "key:$key, before change:$defInt, after change, value:2")
            return 2 //new value
        }
        if (MatrixEnum.clicfg_matrix_trace_fps_report_threshold.name == key) {
            return 10000
        }
        if (MatrixEnum.clicfg_matrix_trace_fps_time_slice.name == key) {
            return 12000
        }
        if (ExptEnum.clicfg_matrix_trace_app_start_up_threshold.name == key) {
            return 3000
        }
        return if (ExptEnum.clicfg_matrix_trace_evil_method_threshold.name == key) {
            200
        } else defInt
    }
    override fun get(key: String, defLong: Long): Long {
        //TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
        if (MatrixEnum.clicfg_matrix_trace_fps_report_threshold.name == key) {
            return 10000L
        }
        if (MatrixEnum.clicfg_matrix_resource_detect_interval_millis.name == key) {
            MatrixLog.i(TAG, "$key, before change:$defLong, after change, value:2000")
            return 2000
        }
        return defLong
    }
    override fun get(key: String, defBool: Boolean): Boolean {
        //TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
        return defBool
    }
    override fun get(key: String, defFloat: Float): Float {
        //TODO here return default value which is inside sdk, you can change it as you wish. matrix-sdk-key in class MatrixEnum.
        return defFloat
    }
    companion object {
        private const val TAG = "Matrix.DynamicConfigImplDemo"
    }
}

1.6 选择程序启动的位置对 Matrix 进行初始化,如在 Application 的继承类中, Init 核心逻辑如下:

 Matrix.Builder builder = new Matrix.Builder(application); // build matrix
  builder.patchListener(new TestPluginListener(this)); // add general pluginListener
  DynamicConfigImplDemo dynamicConfig = new DynamicConfigImplDemo(); // dynamic config
  // init plugin 
  IOCanaryPlugin ioCanaryPlugin = new IOCanaryPlugin(new IOConfig.Builder()
                    .dynamicConfig(dynamicConfig)
                    .build());
  //add to matrix               
  builder.plugin(ioCanaryPlugin);
  //init matrix
  Matrix.init(builder.build());
  // start plugin 
  ioCanaryPlugin.start();

2. 改造Application子类


2.1 模拟Application卡顿

private fun A() {
        B()
        H()
        L()
        SystemClock.sleep(800)
    }
    private fun B() {
        C()
        G()
        SystemClock.sleep(200)
    }
    private fun C() {
        D()
        E()
        F()
        SystemClock.sleep(100)
    }
    private fun D() {
        SystemClock.sleep(20)
    }
    private fun E() {
        SystemClock.sleep(20)
    }
    private fun F() {
        SystemClock.sleep(20)
    }
    private fun G() {
        SystemClock.sleep(20)
    }
    private fun H() {
        SystemClock.sleep(20)
        I()
        J()
        K()
    }
    private fun I() {
        SystemClock.sleep(20)
    }
    private fun J() {
        SystemClock.sleep(6)
    }
    private fun K() {
        SystemClock.sleep(10)
    }
    private fun L() {
        SystemClock.sleep(10000)
    }

2.2 Application.onCreate()调用卡顿方法

override fun onCreate() {
  A()
}

2.3 反射获取ActivityThread的mHandler

override fun attachBaseContext(base: Context?) {
      super.attachBaseContext(base)
      println("zijiexiaozhan MyApp attachBaseContext")
      time1 = SystemClock.uptimeMillis()
      time3 = System.currentTimeMillis()
      try {
          val forName = Class.forName("android.app.ActivityThread")
          val field = forName.getDeclaredField("sCurrentActivityThread")
          field.isAccessible = true
          val activityThreadValue = field[forName]
          val mH = forName.getDeclaredField("mH")
          mH.isAccessible = true
          val handler = mH[activityThreadValue]
          mHandler = handler as Handler
      } catch (e: Exception) {
      }
}

2.4 将原来的onCreate的方法调用转入匿名内部类调用

inner class ApplicationTask : Runnable {
    override fun run() {
        A()
    }
}

2.5 重写Application onCreate方法

override fun onCreate() {
    super.onCreate()
    //重点
    mHandler.postAtFrontOfQueue(ApplicationTask())
}

3.运行,快速定位


3.1 关键字"Trace_EvilMethod"查找日志


tag[Trace_EvilMethod]type[0];key[null];content["machine":"MIDDLE","cpu_app":0,"mem":3822452736,"mem_free":1164132,"detail":"NORMAL","cost":1344,"usage":"0.37%","scene":"default","stack":"0,1048574,1,1344\n1,5471,1,1338\n2,17582,1,1338\n3,17558,1,1338\n4,17560,1,379\n5,17562,1,160\n6,17563,1,17\n6,17566,1,20\n6,17568,1,20\n5,17569,1,20\n4,17573,1,56\n5,17575,1,21\n5,17576,1,5\n5,17578,1,10\n4,17580,1,102\n","stackKey":"17558","tag":"Trace_EvilMethod","process":"com.peter.viewgrouptutorial","time":1624837969986]

3.2 解析日志 打印卡顿堆栈

android.os.Handler dispatchMessage 1344
.com.peter.viewgrouptutorial.MyApp$ApplicationTask run 1338
..com.peter.viewgrouptutorial.MyApp access$A 1338
...com.peter.viewgrouptutorial.MyApp A 1338
....com.peter.viewgrouptutorial.MyApp B 379
.....com.peter.viewgrouptutorial.MyApp C 160
......com.peter.viewgrouptutorial.MyApp D 17
......com.peter.viewgrouptutorial.MyApp E 20
......com.peter.viewgrouptutorial.MyApp F 20
.....com.peter.viewgrouptutorial.MyApp G 20
....com.peter.viewgrouptutorial.MyApp H 56
.....com.peter.viewgrouptutorial.MyApp I 21
.....com.peter.viewgrouptutorial.MyApp J 5
.....com.peter.viewgrouptutorial.MyApp K 10
....com.peter.viewgrouptutorial.MyApp L 102



相关文章
|
5月前
|
编解码 Java 测试技术
『App自动化测试之Appium应用篇』| uiautomator + accessibility_id定位方法完全使用攻略
『App自动化测试之Appium应用篇』| uiautomator + accessibility_id定位方法完全使用攻略
244 0
|
4月前
|
XML 监控 安全
Android App性能优化之卡顿监控和卡顿优化
本文探讨了Android应用的卡顿优化,重点在于布局优化。建议包括将耗时操作移到后台、使用ViewPager2实现懒加载、减少布局嵌套并利用merge标签、使用ViewStub减少资源消耗,以及通过Layout Inspector和GPU过度绘制检测来优化。推荐使用AsyncLayoutInflater异步加载布局,但需注意线程安全和不支持特性。卡顿监控方面,提到了通过Looper、ChoreographerHelper、adb命令及第三方工具如systrace和BlockCanary。总结了Choreographer基于掉帧计算和BlockCanary基于Looper监控的原理。
67 3
|
5月前
|
JSON Java 定位技术
【Android App】GPS获取定位经纬度和根据经纬度获取详细地址讲解及实战(附源码和演示 超详细)
【Android App】GPS获取定位经纬度和根据经纬度获取详细地址讲解及实战(附源码和演示 超详细)
1510 0
|
5月前
|
XML 数据格式
Xpath高阶定位技巧,轻松玩转App测试元素定位!
XPath是一种用于XML文档中节点定位的语言,支持逻辑运算符(and、or、not)、轴定位、谓词和内置函数。
75 0
|
5月前
|
测试技术 Android开发 索引
XPath定位如何在App自动化测试中大显神威
本文介绍了如何在Appium中使用XPath进行自动化App测试。通过淘宝App实例,展示了XPath在定位元素上的应用,包括基础定位(如通过text、resource-id、class和content-desc属性),contains模糊定位,组合定位以及层级定位(如父、子、兄弟和祖元素定位)。XPath的灵活性和强大功能使得在Appium中高效地定位元素成为可能,从而提升移动应用的测试效率。
55 0
|
5月前
|
XML Java 定位技术
【Android App】定位导航GPS中开启手机定位功能讲解及实战(附源码和演示 超详细)
【Android App】定位导航GPS中开启手机定位功能讲解及实战(附源码和演示 超详细)
248 0
|
算法 数据库 索引
App Inventor 2 算法之二分算法(Binary Search)实现,快速查找定位
二分算法(Binary Search)是生活中非常常用的折半算法,能解决快速查找、快速定位的问题,主要用到数学和逻辑代码块。 本示例程序演示了采用普通遍历的方式和二分的方式分别需要几次能够猜中随机给出的数字。
139 0
|
XML JavaScript 测试技术
软件测试|App自动化控件定位
软件测试|App自动化控件定位
93 0
软件测试|App自动化控件定位
|
XML JavaScript Java
app自动化测试(Android)--App 控件定位
app自动化测试(Android)--App 控件定位
172 0
app自动化测试(Android)--App 控件定位
|
存储 Android开发 UED
Android 音乐APP(二)启动白屏优化、定位当前播放歌曲
Android 音乐APP(二)启动白屏优化、定位当前播放歌曲
265 0
Android 音乐APP(二)启动白屏优化、定位当前播放歌曲
下一篇
无影云桌面