版本沖突天天見
最近刻蟹,和 AS 君的某個(gè)紅色小錯(cuò)誤非常有緣分跃须,經(jīng)常見面蚤吹。
從報(bào)錯(cuò)信息中,得知是沖突原因是 support-annotations 有兩個(gè)版本充易, 26.1.0 和 27.1.1 梗脾。
感覺瞬間就找到了問題有沒有?
Too young too simple ,sometime naive 蔽氨。
因?yàn)?build.gradle 中并沒有對(duì) support-annotations 的明顯依賴藐唠。
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
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'
}
依賴樹溯源
對(duì)于以上問題,處理 AS 爆紅的多年經(jīng)驗(yàn)告訴我鹉究,需要打印項(xiàng)目的依賴樹的時(shí)候到了!
./gradlew :app:dependencyInsight --dependency support-annotations --configuration debugAndroidTestCompileClasspath
使用 dependencyInsight 命令支持查看某個(gè)庫在項(xiàng)目中的版本依賴踪宠。報(bào)錯(cuò)信息說明沖突發(fā)生在 for app 和 for test app 自赔,因此選擇打印 debugAndroidTestCompileClasspath 配置下的依賴樹。
拿到依賴樹柳琢,結(jié)合項(xiàng)目的 build.gradle 绍妨,對(duì)比得到造成沖突是這仨庫的鍋:
com.android.support:appcompat-v7:26.1.0 ---> (26.1.0)
com.android.support.test:runner:1.0.2 ---> (27.1.1)
com.android.support.test.espresso:espresso-core:3.0.2 ---> (27.1.1)
原因找到了润脸,問題就很好解決了,排除掉沖突的其中一個(gè)版本即可他去。因?yàn)?support 庫一般要保持統(tǒng)一版本毙驯,所以我選擇排除其他庫的沖突版本。
androidTestImplementation ('com.android.support.test:runner:1.0.2'){
exclude group: 'com.android.support'
}
androidTestImplementation ('com.android.support.test.espresso:espresso-core:3.0.2'){
exclude group: 'com.android.support'
}
另一個(gè)方法
開發(fā)工作中灾测,遇到依賴庫版本沖突問題爆价,是很常見的問題,通過以上步驟基本都能解決媳搪,但是有時(shí)候項(xiàng)目很龐大铭段,找起來挺費(fèi)事。針對(duì)這種情況秦爆,有一個(gè)簡單粗暴的方法序愚。
在 project 的 build.gradle 中添加如下的代碼。作用是在項(xiàng)目構(gòu)建時(shí)等限,遍歷所有依賴爸吮,然后 com.android.support 包下的依賴替換同一個(gè)版本。
buildscript {
subprojects {
project.configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.android.support'
&& !details.requested.name.contains('multidex') ) {
details.useVersion "26.1.0"
}
}
}
}
}
這個(gè)方法望门,解決的很有效率形娇,但是每次構(gòu)建的時(shí)候,多了一個(gè)遍歷過程怒允,會(huì)加長構(gòu)建時(shí)間埂软。因此,只建議應(yīng)急用纫事,推薦使用 exclude 關(guān)鍵字排除勘畔。
以上就是最近一次解決問題的經(jīng)驗(yàn)分享,希望對(duì)大家有幫助丽惶。
小伙伴們?nèi)绻X得還不錯(cuò)炫七,或者發(fā)現(xiàn)了錯(cuò)誤,或者有更好的想法钾唬。都請(qǐng)不要害羞万哪,大聲說出來,作者熱烈歡迎你的點(diǎn)贊和留言吶抡秆。