参考:
Gradle依赖项学习总结,dependencies、transitive、force、exclude的使用与依赖冲突解决
[Gradle中文教程系列]-跟我学Gradle-5.3:依赖-管理依赖的版本(传递(transitive)\排除(exclude)\强制(force)\动态版本(+))
android studio sync报错:
Error:Execution failed for task ':app:preDebugAndroidTestBuild'.
> Conflict with dependency 'com.android.support:support-annotations' in project ':app'.
Resolved versions for app (25.3.1) and test app (27.1.1) differ.
See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.
出错原因:
androidTestCompile的库依赖于com.android.support:support-annotations,
和项目自带的com.android.support:support-annotations版本不一致导致的
解决方法一:强制修改androidTestCompile依赖版本
build.gradle的android{}内添加:
configurations.all {//修改
resolutionStrategy.force 'com.android.support:support-annotations:26.1.0'
}
dependencies {
androidTestCompile('com.android.support.test:runner:0.2')
androidTestCompile('com.android.support.test:rules:0.2')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.1')
}
force:强制设置某个模块的版本。
解决方法二:不编译androidTestCompile依赖的冲突库
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.1.0'
testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:1.0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
androidTestCompile 'com.android.support:support-annotations:25.3.1' //添加
}
改成以下:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.1.0'
testCompile 'junit:junit:4.12'
androidTestCompile ('com.android.support.test:runner:1.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})//添加
androidTestCompile('com.android.support.test.espresso:espresso-core:3.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})//添加
}
Exclude可以设置不编译指定的模块
exclude后的参数有group和module,可以分别单独使用,会排除所有匹配项。
新建项目默认:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
可见:项目默认使用的是exclude方法