1. 程式人生 > >com.android.support衝突的解決辦法

com.android.support衝突的解決辦法

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes

如果很多第三方包都有與support包衝突的話,可以在build檔案新增以下程式碼,這樣就不用一個一個依賴的exclude了:

//強制所有的第三方包使用指定版本的support包:
configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == 'com.android.support') {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion '27.1.1'
            }
        }
    }
}

另外當我們自己建立library給別人使用時,如果需要依賴com.android.support的話,建議用provided的方式依賴(android studio3.0中更改為compileOnly),這樣只會在編譯時有效,不會參與打包。從根源上避免了上面衝突,對於SDK提供者尤其注意哈。

    provided 'com.android.support:appcompat-v7:26.1.0'
    provided 'com.android.support:design:26.1.0'
    provided 'com.android.support:support-vector-drawable:26.1.0'

值得額外說明的是:

在Android studio3.0中,compile依賴關係已被棄用,被implementation和api替代,provided被compile only替代,apk被runtime only替代,剩下的看名字就知道了。

我們先來看看implementation和api的區別:

api:跟2.x版本的 compile完全相同

implementation:只能在內部使用此模組,比如我在一個libiary中使用implementation依賴了gson庫,然後我的主專案依賴了libiary,那麼,我的主專案就無法訪問gson庫中的方法。這樣的好處是編譯速度會加快,推薦使用implementation的方式去依賴,如果你需要提供給外部訪問,那麼就使用api依賴即可

還不熟悉2.x版本依賴的可以看看下面的說明,括號裡對應的是3.0版本的依賴方式。

compile(api)

這種是我們最常用的方式,使用該方式依賴的庫將會參與編譯和打包。 
當我們依賴一些第三方的庫時,可能會遇到com.android.support衝突的問題,就是因為開發者使用的compile依賴的com.android.support包,而他所依賴的包與我們本地所依賴的com.android.support包版本不一樣,所以就會報All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes這個錯誤。

provided(compileOnly)

只在編譯時有效,不會參與打包 
可以在自己的moudle中使用該方式依賴一些比如com.android.support,gson這些使用者常用的庫,避免衝突。

apk(runtimeOnly)

只在生成apk的時候參與打包,編譯時不會參與,很少用。

testCompile(testImplementation)

testCompile 只在單元測試程式碼的編譯以及最終打包測試apk時有效。

debugCompile(debugImplementation)

debugCompile 只在debug模式的編譯和最終的debug apk打包時有效

releaseCompile(releaseImplementation)

Release compile 僅僅針對Release 模式的編譯和最終的Release apk打包