原文:https://blog.csdn.net/yuzhiqiang_1993/article/details/78366985
Android Studio3.0正式版已經出來了,相比2.x的版本,Gradle版本也升級為了3.x,編譯速度提高了不少。
在gadle3.0之后,默認的依賴由之前的compile更改為implementation了。
如果我們依然使用compile的話會有如下提示
Configuration ‘compile’ is obsolete and has been replaced with ‘implementation’ and ‘api’.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
告訴我們配置 compile已過時,已被 implementation 和api 取代。
下面我們來看看他們之前的差異:
首先是2.x版本的依賴方式:
再來看看3.0的:
可以看到在gradle3.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(implementation,api)
這種是我們最常用的方式,使用該方式依賴的庫將會參與編譯和打包。
implementation:該依賴方式所依賴的庫不會傳遞,只會在當前module中生效。
api:該依賴方式會傳遞所依賴的庫,當其他module依賴了該module時,可以使用該module下使用api依賴的庫。
當我們依賴一些第三方的庫時,可能會遇到com.android.support沖突的問題,就是因為開發者使用的compile或api依賴的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這個錯誤。
解決辦法可以看這篇博客:com.android.support沖突的解決辦法
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打包。