Android Studio新建项目后出现依赖冲突问题求助
我用Android Studio 3.0.1创建新项目后,遇到了这个错误:
Error:Execution failed for task ':app:preDebugAndroidTestBuild'.
Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.
下面是我的app级build.gradle文件:
apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { minSdkVersion 19 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
以及顶级build.gradle文件:
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }
我参考Stack Overflow的帖子尝试把implementation 'com.android.support:appcompat-v7:26.1.0'改成了implementation 'com.android.support:appcompat-v7:27.1.1',但我的targetSdkVersion是26,按道理不该用27.1.1版本的支持库,想问问该怎么解决这个问题?
别担心,这个问题是因为主应用和测试应用依赖的support-annotations版本不一致导致的,给你几个靠谱的解决办法:
方法一:强制统一所有模块的support-annotations版本
在app级的build.gradle里,新增一个configurations块,强制指定support-annotations的版本为26.1.0,这样主应用和测试应用都会使用同一个版本:
android { // 保留原来的android配置内容 } // 新增这个配置块 configurations.all { resolutionStrategy.force 'com.android.support:support-annotations:26.1.0' } dependencies { // 保留原来的依赖内容 }
方法二:降级测试依赖到适配26版本的兼容包
你当前使用的测试库版本(runner 1.0.2、espresso-core 3.0.2)默认依赖27.x的support库,你可以把它们降级到适配26版本的测试库:
修改dependencies里的androidTestImplementation依赖为:
androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
这两个版本的测试库依赖的是26.x的support-annotations,刚好和你的主应用版本匹配。
方法三:升级compileSdkVersion和targetSdkVersion到27
如果你的项目允许升级SDK版本,这其实是更规范的做法——因为support库的版本应该和compileSdkVersion保持一致。你只需要修改app级build.gradle里的配置:
android { compileSdkVersion 27 defaultConfig { minSdkVersion 19 targetSdkVersion 27 // 同步修改为27 // 保留其他配置内容 } // 保留其他配置内容 }
这样使用27.1.1的support库就完全合理了,还能获得27版本SDK的新特性和修复。
你可以根据自己的项目需求选择其中一种方法,我个人更推荐方法二或者方法三,前者不用改动SDK版本,后者更符合Android的版本规范。
内容的提问来源于stack exchange,提问作者Learning Always

