Android 性能优化 - 启动速度优化

启动的类型

通常分为,冷启动和热启动html

冷启动:启动时,后台没有任何该应用的进程,系统须要从新建立一个进程,并结合启动参数启动该应用。python

热启动:启动时,系统已经有该应用的进程(好比按 home 键临时退出该应用)下启动该应用。android

如何获取启动时间

  1. adb 命令

adb shell am start -S -W 包名/启动类的全名git

adb shell am start -S -W xxx/xxxActivity
Stopping: xxx
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=xxx/xxxActivity }
Status: ok
Activity: xxx/xxxActivity
ThisTime: 770
TotalTime: 770
WaitTime: 848
Complete

ThisTime: 表示最后一个 Activity 启动时间github

TotalTime: 表示启动过程当中,全部的 Activity 的启动时间shell

WaitTime: 表示应用进程的建立时间 + TotalTime浏览器

通常咱们关注 TotalTime 就行了。app

另外,谷歌在 Android4.4(API 19)上也提供了测量方法,在 logcat 中过滤 Displayed 字段也能够看到启动时间异步

2021-04-06 19:25:52.803 2210-2245 I/ActivityManager: Displayed xxx/xxxActivity: +623ms工具

+623ms 就是Activity 的启动时间。

  1. 时间戳

时间戳的方法基于如下的 2 个知识点。

  • 应用进程刚建立,会调用 Application 的 onCreate 方法。
  • 首次进入一个 Activity 后会在 onResume() 方法后面调用 onWindowsFocusChange 方法。

结合这 2 个特性,咱们能够在 A Application 的 onCreate() 方法和 Activity 的 onWindowsFocusChange 方法里面,经过时间戳来获取应用的冷启动时间。

如何监控启动过程

  1. systrace

systrace 是一个功能很强大的工具,除了能够查看卡顿问题,也能够用来查看应用的启动问题。使用示例以下:

python $ANDROID_HOME/platform-tools/systrace/systrace.py gfx view wm am pm ss dalvik app sched -b 90960 -a 你的包名 -o test.log.html

用 Google 浏览器打开 test.log.html 就能够看到详细的启动信息。

  1. Debug 接口
package android.os;
...
class Debug {
    ...
    public static void startMethodTracingSampling(String tracePath, int bufferSize, int intervalUs) {

    }
    public static void startMethodTracing(String tracePath, int bufferSize) {

    }
}

利用 Debug 类的这两个方法,能够生成一个 trace 文件,这个 trace 文件,能够直接在 AS 里面打开,能够看到从 startMethodTracingSamplingstartMethodTracing 过程当中的方法调用等信息,也能够较好的分析启动问题。

通常有那些优化方法

  1. 耗时操做放到异步进程

好比文件解压、读写等耗时 IO 操做能够新开一个线程来执行。

  1. 延时初始化

即暂时不适用的工具类等延后到使用的时候再去初始化。好比从 xml 里面读取颜色,能够考虑在使用的时候再去读取和解析。

  1. 线程优化

线程的建立须要消耗较多的系统系统资源,减小线程的建立。能够考虑共用一个线程池。

如何检测线程的建立,能够参考我个开源库 performance

联系我

相关文章
相关标签/搜索