implementation:只能在内部使用此模块,比如我在一个libiary中使用implementation依赖了gson库,然后我的主项目依赖了libiary,那么,我的主项目就无法访问gson库中的方法。这样的好处是编译速度会加快,推荐使用implementation的方式去依赖,如果你需要提供给外部访问,那么就使用api依赖即可
api:该依赖方式会传递所依赖的库,当其他module依赖了该module时,可以使用该module下使用api依赖的库。
当我们依赖一些第三方的库时,可能会遇到com.android.support冲突的问题,就是因为开发者使用的compile或api依赖的com.android.support包与我们本地所依赖的com.android.support包版本不一样,所以就会报All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes这个错误。
解决方法(同样的适用于其他的依赖冲突。)
修改自己项目中的com.android.support的版本号,与所依赖的库版本号一致,但是当我们依赖的库中的com.android.support版本号有好几个版本就不行了。(不推荐)
依赖第三方库时候排除掉对com.android.support包的依赖,这样自己的项目随便依赖什么版本都可以,但是这种方法需要你先找到哪些库存在冲突
通过groovy脚本强制修改冲突的依赖库版本号 (推荐)
将项目迁移至AndroidX(推荐)
排除依赖法
我们先来看第二种方法
首先我们需要知道哪些库存在着冲突
点击Terminal 输入 gradlew -q app:dependencies 回车即可将app中所依赖的库展示出来
然后找出存在冲突的依赖库,这里我们可以看到是arouter中的一个依赖存在版本号不一致的情况,我们只需要将冲突的依赖排除掉即可。
exclude group:表示只要包含com.android.support的都排除
api("com.afollestad.material-dialogs:core:0.9.5.0") {
exclude group: 'com.android.support'
}
module:删排除group中的指定module
api("com.afollestad.material-dialogs:core:0.9.5.0") {
exclude group: 'com.android.support', module: 'support-v13'
exclude group: 'com.android.support', module: 'support-vector-drawable'
}
另外还有一个建议,在我们自己创建library给别人使用时,如果需要依赖com.android.support的话,建议用compileOnly的方式依赖,这样只会在编译时有效,不会参与打包。以免给使用者带来不便。
通过Grovvy脚本修改版本号解决冲突
在其存在冲突的module中的build.gradle文件中加入下面代码,原理就是通过遍历所有依赖,并修改指定库的版本号
其中
requested.group == ‘com.android.support’ com.android.support表示要修改的依赖库
details.useVersion ‘28.0.0’ 28.0.0表示要修改的版本号
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'
}
}
}
}
将项目迁移至AndroidX(推荐)
compileOnly
只在编译时有效,不会参与打包
可以在自己的moudle中使用该方式依赖一些比如com.android.support,gson这些使用者常用的库,避免冲突。
runtimeOnly
只在生成apk的时候参与打包,编译时不会参与,很少用。
testImplementation
testCompile 只在单元测试代码的编译以及最终打包测试apk时有效。
debugImplementation
debugCompile 只在debug模式的编译和最终的debug apk打包时有效
releaseImplementation
Release compile 仅仅针对Release 模式的编译和最终的Release apk打包。