關鍵詞說明
自Android studio版本更新至3.0后,連帶着com.android.tools.build:gradle 工具也升級到了3.0.0,在3.0.0中使用了最新的Gralde 4.0 里程碑版本作為gradle的編譯版本,該版本gradle編譯速度有所加速;
Gradle新老版本關鍵字
4.x+版本配置 | 已棄用配置 |
api
|
compile |
implementation | compile |
compileOnly | provided |
runtimeOnly | apk |
testImplementation | testCompile |
androidTestImplementation | androidTestCompile |
debugImplementation | debugCompile |
releaseImplementation | releaseCompile |
- api
與compile對應,功能完全一樣,會添加依賴到編譯路徑,並且會將依賴打包到輸出(aar或apk),與implementation不同,這個依賴可以傳遞,其他module無論在編譯時和運行時都可以訪問這個依賴的實現,也就是會泄漏一些不應該不使用的實現。舉個例子,A依賴B,B依賴C,如果都是使用api配置的話,A可以直接使用C中的類(編譯時和運行時),而如果是使用implementation配置的話,在編譯時,A是無法訪問C中的類的。
- implementation
與compile對應,會添加依賴到編譯路徑,並且會將依賴打包到輸出(aar或apk),但是在編譯時不會將依賴的實現暴露給其他module,也就是只有在運行時其他module才能訪問這個依賴中的實現;
簡單的說,就是使用implementation指令的依賴不會傳遞;
使用這個配置,可以顯著提升構建時間,因為它可以減少重新編譯的module的數量。Google建議盡量使用這個依賴配置;
- compileOnly
與provided對應,Gradle把依賴加到編譯路徑,編譯時使用,不會打包到輸出(aar或apk)。這可以減少輸出的體積,在只在編譯時需要,在運行時可選的情況,很有用
- apk
只在生成apk的時候參與打包,編譯時不會參與,很少用。
- testImplementation
只在單元測試代碼的編譯以及最終打包測試apk時有效。
- androidTestImplementation
只在Android相關單元測試代碼的編譯以及最終打包測試apk時有效。
- debugImplementation
只在 debug 模式的編譯和最終的 debug apk 打包時有效
- releaseImplementation
僅僅針對 Release 模式的編譯和最終的 Release apk 打包。
引入依賴的基本方式
dependencies { implementation project(':projectABC') implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'androidx.appcompat:appcompat:1.0.2' }
1.本地項目依賴 --> module依賴
dependencies { implementation project(':projectABC') }
2.本地二進制依賴 --> jar和so等文件
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) }
這種依賴方式是依賴工程中libs目錄下的jar等文件;
也可進行單獨某個文件的引用
dependencies { implementation files('libs/aaa.jar', 'libs/bbb.jar') implementation files('x/y/z/ccc.jar') }
注意:Gradle的路徑是相對於build.gradle文件來讀取的,所以上面是這樣的相對路徑
dependencies { implementation 'androidx.appcompat:appcompat:1.0.2' }
完整寫法:
dependencies { implementation group: 'androidx.appcompat', name:'appcompat', version:'1.0.2' }
引入依賴其他方式
1.根據Task類型引入
debug,release,test包的引入方式
dependencies { testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-beta-2' releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:2.0-beta-2' }
2.排除引用
有時候為了解決引入的沖突,需要在引入遠端包的同時排除這些包的某幾個依賴
dependencies { implementation ('com.github.bumptech.glide:glide:4.9.0'){ exclude group:'com.android.support', module: 'support-fragment' exclude group:'com.android.support', module: 'support-core-ui' exclude group:'com.android.support', module: 'support-compat' exclude group:'com.android.support', module: 'support-annotations' } }