ProfileInstaller:安装 Baseline Profile · AndroidX 源码指南
AAndroidX 源码指南
后台与启动
后台与启动 · androidx.work

ProfileInstaller:安装 Baseline ProfileWork 2.12.0-beta01

分清 profile 的生成、打包、安装和验证。

最后更新 2026-08-01

完整链路

1. Macrobenchmark 跑关键路径 → 生成 profile 规则
2. 应用构建把 profile 打包进 APK/AAB
3. ProfileInstaller 设备端安装 profile
4. ART 据此提前编译热点路径
5. release 构建实测性能

ProfileInstaller 的职责:读取 APK 中已有的 baseline profile,按设备运行时格式转码并写入系统可读取位置。它不会替你决定哪些方法应进入 profile(那是 Macrobenchmark 的事)。

复制即用:依赖

implementation("androidx.profileinstaller:profileinstaller:1.5.0-alpha01")

默认通过 ProfileInstallerInitializer 延迟触发安装——只加依赖即可

手动安装时机

禁用 initializer 后,应用自行调用:

// 合适时机(如首启后台线程)
ProfileInstaller.writeProfile(context)

陷阱:禁用 initializer 又不手动调用 → 只加依赖没有安装效果。

验证编译状态

val result = ProfileVerifier.calculateProfileStatus(context)
// result.profileInstallResultCode 等

“profile 已安装” ≠ “启动时间必然达标”:

  • 基准设备、构建类型(release vs debug)、测量流程决定结论。
  • profile 在 debug 构建上通常不生效。

生成 profile(配合 Macrobenchmark)

// baseline-profile 模块(Gradle Managed Device)
class BaselineProfileGenerator {
    @get:Rule
    val baselineProfileRule = BaselineProfileRule()

    @Test
    fun generate() {
        baselineProfileRule.collect(
            packageName = "com.example.app",
            profileBlock = {
                startActivityAndWait()
                pressHome()
            },
        )
    }
}

常见陷阱

  • 只加依赖不验证:默认 initializer 会装,但要确认 release 构建生效。
  • 禁用 initializer 忘手动:无安装效果。
  • debug 构建看效果:profile 在 debug 无效,看 release。
  • 把 profile 当魔法:方法选择靠 Macrobenchmark,不是 ProfileInstaller。

复制即用

// 需要延迟/手动安装时
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 后台线程安装(不要在启动关键路径阻塞)
        lifecycleScope.launch(Dispatchers.IO) {
            ProfileInstaller.writeProfile(applicationContext)
        }
    }
}

要点

  • 生成(Macrobenchmark)→ 打包 → 安装(ProfileInstaller)→ 实测。
  • 默认 initializer 自动装;禁用后要手动 writeProfile
  • 性能结论看 release + 基准设备实测。
  • profile 选方法靠 Macrobenchmark,ProfileInstaller 只负责安装。

相关页面