解决 androidx.core:core 依赖导致的构建失败
问题原因
构建 Android 项目时出现以下错误:
Execution failed for task ':app:checkDebugAarMetadata'
A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
Dependency 'androidx.core:core:1.15.0-alpha01' requires libraries and applications that
depend on it to compile against version 35 or later of the
Android APIs.
:app is currently compiled against android-34.
核心问题分析:
- 依赖库
androidx.core:core:1.15.0-alpha01
要求编译 SDK 版本 ≥35 (Android 15) - 当前项目的
compileSdk
版本为 34(Android 14) - Android Gradle 插件 8.1.1 最高支持到 SDK 34
- 尝试强制降级依赖版本无效,说明存在其他依赖引发了版本冲突
解决方案
方案1:降级依赖版本(推荐)
在 build.gradle
文件中明确指定稳定版本:
groovy
android {
// ...
compileSdk = 34
targetSdk = 34
}
dependencies {
// 明确指定 Stable 版本
implementation "androidx.core:core:1.13.1"
implementation "androidx.core:core-ktx:1.13.1"
}
方案2:处理传递依赖(当方案1无效时)
使用 resolutionStrategy 强制统一依赖版本:
groovy
dependencies {
// ...
}
configurations.all {
resolutionStrategy {
// 强制指定 core 依赖版本
force "androidx.core:core:1.13.1"
force "androidx.core:core-ktx:1.13.1"
}
}
方案3:定位版本冲突源
查找哪个模块引入了 1.15.0-alpha01 依赖:
bash
./gradlew app:dependencyInsight --dependency androidx.core:core
结果示例:
\--- project :app
\--- com.module:library:1.0.0
\--- androidx.core:core:1.15.0-alpha01
发现问题后,可对该依赖进行排除:
groovy
implementation("com.module:library:1.0.0") {
exclude group: 'androidx.core', module: 'core'
}
方案4:更新到 SDK 35(仅当 Android 15 稳定时)
适用于需要最新功能的场景:
- 在 Android Studio 的 SDK Manager 安装 Android 15 SDK
- 修改项目配置:
groovy
android {
compileSdk = 35
targetSdk = 35
}
常见陷阱与解决方案
仍然出现 1.15.0-alpha01 错误
danger
即使明确指定了低版本,但其他依赖仍可能引入高版本
解决方法:
- 使用
./gradlew app:dependencies
检查依赖树 - 对所有引用 core 的依赖添加 resolutionStrategy:groovy
configurations.all { resolutionStrategy.eachDependency { details -> if (details.requested.group == 'androidx.core') { details.useVersion "1.13.1" } } }
Google Play 上架注意事项
warning
targetSdk 低于 33 的应用无法在 Google Play 上架(2023年8月起)
正确配置:
diff
android {
compileSdk = 34
- targetSdk = 32 // 过低的版本
+ targetSdk = 34 // 当前推荐的最低可上架版本
}
避免不稳定依赖
tip
当遇到类似问题时应:
1. 避免使用 `+` 或通配符版本号
2. 不使用 `alpha`、`beta` 等预览版本
3. 优先选择 Maven Repository 中标记为 "Stable" 的版本
最佳实践总结
使用稳定版本:在 build.gradle 中显式声明所有依赖版本
groovy// 推荐 ✅ implementation "androidx.core:core-ktx:1.13.1" // 避免 ⛔ implementation "androidx.core:core-ktx:+"
定期检查更新:每季度检查依赖更新
bash./gradlew dependencyUpdates -Drevision=release
启用版本稳定锁定:
gradle# 开启 Gradle 版本锁定 android.lockAllDependencies=strict
当遵循这些实践后,项目将保持稳定的构建状态,避免因依赖版本冲突导致的构建失败。