如何解决Android编译报错:com.android.support版本不一致问题
问题重现
我有一个Android项目的模块级build.gradle代码如下:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion '22.0.1' defaultConfig { applicationId "com.parse.starter" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" multiDexEnabled true } dexOptions { javaMaxHeapSize "4g" } buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.parse.bolts:bolts-tasks:1.3.0' compile 'com.parse:parse-android:1.13.0' compile 'com.google.android.gms:play-services:9.4.0' compile 'com.android.support:multidex:1.0.0' }
编译时触发了以下错误:
All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 23.4.0, 23.0.0. Examples include com.android.support:animated-vector-drawable:23.4.0 and com.android.support:mediarouter-v7:23.0.0 less... (Ctrl+F1) There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion).
尝试添加代码解决但无效,求可行的修复方案。
解决方案
我来给你拆解下这个问题:错误的本质是项目中同时存在不同版本的Android Support Library——你直接声明了appcompat-v7:23.4.0,但某个第三方依赖(大概率是完整版的play-services:9.4.0)间接引入了旧版本的mediarouter-v7:23.0.0,版本不一致导致了Gradle的冲突检测报错。
你可以按以下步骤彻底解决:
1. 强制统一所有Support Library版本
在模块级build.gradle的android代码块之后,添加一段配置代码,强制所有com.android.support库(除了multidex)使用你指定的23.4.0版本:
configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> def requested = details.requested if (requested.group == 'com.android.support') { // 排除multidex,因为它的版本规则和其他Support库不同 if (!requested.name.startsWith("multidex")) { details.useVersion '23.4.0' } } } }
这段代码会自动替换所有间接引入的Support库版本,和你声明的appcompat-v7保持完全一致,从根源上解决版本冲突。
2. 优化Play Services依赖(可选但推荐)
你当前引入了完整的play-services:9.4.0,这会包含数十个你可能根本用不到的模块(比如健身、支付、穿戴等),不仅容易引发依赖冲突,还会大幅增加APK体积。建议只引入你实际需要的子模块,比如:
- 用地图功能:
compile 'com.google.android.gms:play-services-maps:9.4.0' - 用位置服务:
compile 'com.google.android.gms:play-services-location:9.4.0' - 用身份验证:
compile 'com.google.android.gms:play-services-auth:9.4.0'
这样能减少间接引入的依赖数量,降低后续出现冲突的概率。
3. 排查冲突根源(可选)
如果你想确认到底是哪个依赖引入了旧版本的Support库,可以在Android Studio的Terminal中执行以下命令:
./gradlew app:dependencies
在输出的依赖树中,找到com.android.support:mediarouter-v7:23.0.0的依赖路径,就能明确冲突的来源,方便后续做更精准的优化。
内容的提问来源于stack exchange,提问作者kavan

