1. 升级前的版本环境检查
1.1 现象识别
升级 Compose Compiler 时,最常见的前置现象是构建失败或运行时异常,且错误信息往往指向版本不匹配。典型现象包括:
- Kotlin 编译错误:Gradle 同步失败,提示
kotlin-compiler-embeddable版本冲突。 - Compose 注解处理器错误:
@Composable函数无法识别,提示需要更新 Compose Compiler。 - AGP 版本冲突:构建时抛出
Android Gradle plugin requires Java 11或更高版本。 - Gradle 版本不支持:
Gradle 7.x 与 AGP 8.x 不兼容,导致任务无法执行。
注意:升级前若未检查版本矩阵,极易出现“连锁不兼容”——即 Compose Compiler 依赖 Kotlin 版本,而 Kotlin 版本又依赖 AGP/Gradle,最终导致数十个依赖需要降级或升级。
1.2 数据采集
在排查前,需采集当前项目的四个关键版本号。推荐优先使用 Gradle 任务或脚本输出,避免手动查找。
| 组件 | 采集命令 / 方法 | 输出示例 |
|---|---|---|
| Kotlin 版本 | ./gradlew properties | grep kotlinVersion 或 kotlin("jvm") version | kotlinVersion=1.9.22 |
| Compose Compiler | 查看 composeOptions { kotlinCompilerExtensionVersion } | 1.5.11 |
| AGP 版本 | ./gradlew properties | grep androidPluginVersion | 8.2.2 |
| Gradle 版本 | ./gradlew --version | Gradle 8.4 |
若环境变量或脚本不可用,也可直接查看 build.gradle.kts 或 libs.versions.toml 中的版本声明。
1.3 原因定位
版本兼容性问题根因在于 Compose Compiler 与 Kotlin 的强绑定关系,以及 AGP/Gradle 之间的演进节奏不一致。下表列出截至 2025 年初的已知不兼容组合(深色背景行表示高风险):
| Compose Compiler | Kotlin | AGP | Gradle | 不兼容情况 |
|---|---|---|---|---|
| 1.5.x | 1.9.22 | 8.2.x | 8.4+ | 支持良好(安全基线) |
| 1.6.0 | 2.0.0 | 8.3.x | 8.5+ | Kotlin 2.0 需 Compose Compiler 1.6.0+,否则编译中断 |
| 1.4.x | 1.9.0 | 8.1.x | 8.2 | AGP 8.1 不兼容 Gradle 8.3+ |
| 1.3.x | 1.8.10 | 7.4.x | 7.6 | 需 Java 11,Gradle 7.6 与 AGP 7.4 已过时 |
| 1.6.1 | 2.0.10 | 8.4.0 | 8.6 | 若 Kotlin 2.0.10 与 Compose 1.6.1 搭配,需同时升级 AGP 至 8.4 |
判断规则:优先检查 Compose Compiler 与 Kotlin 的对应关系(官方映射表),再检查 AGP 与 Gradle 的兼容性。若任意一环不匹配,即需整体调整。
1.4 修复动作
执行快速检查脚本,在项目根目录创建 checkCompatibility.sh(Linux/macOS)或使用 Gradle 任务:
#!/bin/bash
# 快速检查脚本:输出关键版本并打印兼容状态
echo "=== Compose Compiler 环境检查 ==="
KOTLIN_VERSION=$(./gradlew properties -q | grep "kotlinVersion" | awk -F'=' '{print $2}')
COMPOSE_VERSION=$(./gradlew properties -q | grep "kotlinCompilerExtensionVersion" | awk -F'=' '{print $2}')
AGP_VERSION=$(./gradlew properties -q | grep "androidPluginVersion" | awk -F'=' '{print $2}')
GRADLE_VERSION=$(./gradlew --version | grep "Gradle " | awk '{print $2}')
echo "Kotlin: $KOTLIN_VERSION"
echo "Compose Compiler: $COMPOSE_VERSION"
echo "AGP: $AGP_VERSION"
echo "Gradle: $GRADLE_VERSION"
# 简易规则检查(示例)
if [[ "$COMPOSE_VERSION" == "1.5"* ]] && [[ "$KOTLIN_VERSION" != "1.9.22" ]]; then
echo "⚠️ 警告: Compose Compiler 1.5.x 推荐 Kotlin 1.9.22"
fi
if [[ "$COMPOSE_VERSION" == "1.6."* ]] && [[ "$KOTLIN_VERSION" != "2.0"* ]]; then
echo "❌ 错误: Compose Compiler 1.6.x 必须搭配 Kotlin 2.0.x"
fi
echo "=== 检查完毕 ==="
赋予执行权限并运行:chmod +x checkCompatibility.sh && ./checkCompatibility.sh。根据输出提示调整对应版本。
1.5 复测及预防
版本调整后,依次执行以下步骤确认环境无误:
- 运行
./gradlew clean清除缓存。 - 执行
./gradlew assembleDebug,观察编译是否通过。 - 若部署到设备,运行
./gradlew installDebug,验证运行时未出现Compose internal error或Unsupported Kotlin plugin version。 - 使用官方 Compose Compiler 兼容性矩阵 定期核对。
预防措施:在 gradle.properties 中固化版本号,并通过版本目录(Version Catalog)统一管理,避免人工误改。