Android依賴衝突
前言
實際開發過程中不可避免的會使用到一些第三方,而我們引用的第三方可能會和我們使用的其他庫產生衝突;或者由於其他原因需要對依賴進行剔除。
依賴衝突的解決方法其實很簡單,主要就為以下兩個步驟:
- 依賴分析,找到衝突的依賴。
- 剔除依賴或者強制使用某個版本的依賴。
依賴分析
檢視依賴關係需要用到的命令為: gradlew :[module_name]:dependencies
如需分析工程中app這個module的依賴關係行命令則為 : gradlew :app:dependencies
從下面的關係樹可以看到各個依賴之間的關係,以及依賴版本號合併後的最終版本號
+--- com.android.support:support-core-utils:28.0.0 (*) |||+--- com.android.support:customview:28.0.0 ||||+--- com.android.support:support-annotations:28.0.0 ||||\--- com.android.support:support-compat:28.0.0 (*) |||+--- com.android.support:viewpager:28.0.0 ||||+--- com.android.support:support-annotations:28.0.0 ||||+--- com.android.support:support-compat:28.0.0 (*) ||||\--- com.android.support:customview:28.0.0 (*) |||+--- com.android.support:coordinatorlayout:28.0.0
如果你不想在命令終端中檢視,而是想把依賴關係輸出到檔案中,則可以使用以下命令:
gradlew :[module_name]:dependencies > [output_file]
。
例如將app module的依賴關係輸出到dependence.txt檔案中:
gradlew :app:dependencies > dependence.txt
。

輸出檔案.png
剔除依賴
通過移除某個第三方中特定的依賴。
使用 exclude group:'group_name':module:'module_name'
方式剔除具體依賴,如果沒有指定module_name則該group下所有的依賴都會被剔除,具體使用:
//剔除rxpermissions這依賴中所有com.android.support相關的依賴,避免和我們自己的衝突 implementation 'com.github.tbruyelle:rxpermissions:0.10.2', { exclude group: 'com.android.support' exclude group: 'xxxxx' } //或者剔除 tm_navigation(這裡是本地依賴) 依賴中springview group中指定的library implementation project(path: ':tm_navigation'),{ exclude group: 'com.liaoinstan.springview', module: 'library' }
關於group和module的概念,舉一個例子就清楚了。
例如對於依賴 implementation 'com.android.support:appcompat-v7:27.1.0'
。
group為com.android.support,module為appcompat,版本號為27.1.0,同一個group下面可以有很多module的。
下面這種方式可以批量剔除整個工程中的相關依賴
android{ //.... //剔除工程中所有的該依賴 configurations { all*.exclude group: 'org.hamcrest', module: 'hamcrest-core' } }
強制版本
有時候依賴傳遞層級過深或者數量過多,通過上面的方式則不能達到剔除的效果,這時候強制使用版本
android{ //.... //強制使用2.8.5 configurations.all { resolutionStrategy { force 'com.google.code.gson:gson:2.8.5' } } }