android studio 中Error:Execution failed for task ':app:preDebugAndroidTestBuild'. 的解決辦法
使用AndroidStudio工具建立新的app應用時,根據工具提示進行多個next之後,發現編譯報錯,報錯如下:
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. See https://d.android.com/r/tools/test-apk-dependency-conflicts.html for details.
經過網上查閱,發現提供有很多方法,比如 build->Rebuid-project,該方法只是當前啟動有用,但是如果關閉androidstudio工具重新開啟之後又會重新報錯。
該問題主要是因為在新建的應用中預設依賴了com.android.support:support-annotations包與app版本衝突了,app裡的版本是26.1.0,但是Test app的版本里是27.1.1。可在External Libraries資料夾下面找到該包,發現確實衝突。
最後經過查閱,發現兩種方法可以解決該問題,思路都是一樣的,就是將27.1.1版本號強制轉換為26.1.0,轉換方法如下:
(1)在依賴中強制轉換,在app模組下的build.gradle中dependencies下,新增依賴轉換,主要是下面兩行程式碼
androidTestCompile('com.android.support:support-annotations:26.1.0') { force = true }
全部程式碼為:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 26 defaultConfig { applicationId "baseapp.li.com.baseapp" minSdkVersion 15 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"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version" implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' 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' androidTestImplementation('com.android.support:support-annotations:26.1.0') { force = true } }
(2)在配置中強制轉換,在app模組下的build.gralde中進行配置,其中主要增加了兩行程式碼
configurations.all { resolutionStrategy.force 'com.android.support:support-annotations:26.1.0' }
全部程式碼如下:
apply plugin: 'com.android.application' configurations.all { resolutionStrategy.force 'com.android.support:support-annotations:26.1.0' } android { compileSdkVersion 26 defaultConfig { applicationId "wzt.mytest" minSdkVersion 21 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:26.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' }
以上兩種方法均可解決包名衝突問題。下面這個程式碼code背景不知道怎麼去掉了,容許我調皮一下,應該無大礙。