Android Studio Gradle构建依赖冲突的分析和解决

问题介绍

如果App或者库依赖了很多第三方组件库,那么依赖冲突就再所难免。不同版本的库混在在一起,明显的冲突会导致编译过程中就报错。
不明显的隐含冲突更为严重,因为可以正常构建出app包,但报错可能会在app运行时出现,更加难以处理。

例如下面是构建时的一个报错:

build.gradle: Error: All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 27.1.0. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:exifinterface:27.1.0 [GradleCompatible]

分析哪些库版本冲突了

简单项目可能人工查看就能定位到,但一般项目都依赖了很多三方组件,人工分析查看就无能为力了。实际上Gradle提供了依赖查看树命令,可以方便的将项目中的全部依赖以tree的形式展现出来,非常便于查看:

查看全部配置下的依赖树:
gradlew -q dependencies app:dependencies

查看某个具体配置下的依赖树:
gradlew -q dependencies app:dependencies –configuration debugAndroidTestCompileClasspath
gradlew -q dependencies app:dependencies –configuration debugUnitTestCompileClasspath
gradlew -q dependencies app:dependencies –configuration debugCompileClasspath

gradlew -q dependencies app:dependencies –configuration releaseCompileClasspath
gradlew -q dependencies app:dependencies –configuration releaseUnitTestCompileClasspath
gradlew -q dependencies app:dependencies –configuration releaseRuntimeClasspath

如何解决冲突

1. 通过 DependencyResolve 强制修改版本

1
2
3
4
5
6
7
8
9
10
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion '28.0.0'
}
}
}
}

2. 通过 exclude 排除有问题的版本依赖

1
2
3
4
5
6
7
8
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})

implementation('com.facebook.android:facebook-login:[4,5)') {
// contains com.android.support:v7:27.0.2, included required com.android.support.*:27.1.1 modules
exclude group: 'com.android.support'
}