Android gradle依赖冲突解决办法

1.出现的冲突在这里插入图片描述

2.解决方法(解决方法都跟第三部分依赖树有很大关系,建议结合起来看啦)

方法①

在这里插入图片描述

configurations.all {
    //强制使用某个版本的依赖,若需强制多个依赖,可以逗号分割,
    resolutionStrategy.force 'com.android.support:support-annotations:26.1.0'
}

方法②

在这里插入图片描述

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '26.1.0'
            }
        }
    }
}

方法③

通过 exclude 移除造成冲突的依赖

 androidTestImplementation ('com.android.support.test:runner:1.0.2'){
        exclude group:'com.android.support',module: 'support-annotations'
    }
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:3.0.2'){
        exclude group:'com.android.support',module: 'support-annotations'
    }

这里有个重要的知识点
在这里插入图片描述

3.查看依赖的依赖列表(依赖树)

在android studio的Terminal窗口输入命令

gradlew -q app:dependencies

在这里插入图片描述
可以看到appcompat-v7和runner中都有依赖support-annotations,可以看到冲突存在的位置是26.1.0–>27.1.1

还有一种更简单的方法可以看到冲突所在,在module下的gradle.buildd下添加如下代码,但缺点就是不知道具体它是哪个上层依赖引起的,可以结合起来在 Terminal 打印的日志中直接搜索,可快速定位到冲突所在,毕竟依赖树打印出来是一大串的

configurations.all {
    resolutionStrategy {
        failOnVersionConflict()
    }
}

在这里插入图片描述

4.什么情况下会产生依赖冲突?

如果通过相同的方式引入不同版本的依赖库,默认会选择最新版本,不同的方式引入则会产生依赖冲突。引入的方式有:通过jar/aar、maven(不同的compile也算不同方式,如cmpile和androidTestCompile两者引入的方式不同)
具体可看:
android studio 关于gradle依赖管理的一些知识
了解Android支持库
各种导入方式

猜你喜欢

转载自blog.csdn.net/qq_32963927/article/details/89474676