Gradle依賴庫緩存
Gradle拉取的aar庫保存在本地的~/.gradle文件夾和~/.m2文件夾中。由於早期版本的Gradle在緩存的處理上有些問題,有時會出現aar更新後無法生效的問題,可以通過刪除上面緩存的方式進行修復。
利用Gradle的通知機制
雖然當項目依賴庫有更新之後,Gradle並不會立即通知主項目,但Gradle會給出一種通知機制,即利用Gradle的檢查週期進行check。
configurations.all {
resolutionStrategy.cacheChangingModulesFor(0,'seconds')
}
詳細的官方文檔可以參考下面的網址:
https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html
同時Gradle還提供了在依賴傳遞中強制刷新配置。
dependencies {
compile 'com.android.support:multidex:1.0.1'{
transitive = true
}
}
如果增加一個transitive屬性並設置其值爲true,則會強制刷新遠程庫。
利用Gradle的依賴檢查
利用Gradle提供的task可以很方便的解決依賴問題,使用Gradle指令gradle androidDependencies,可以方便地找到每種buildType下的依賴關係圖。
Gradle依賴傳遞
在使用Gradle aar文件時,會產生依賴庫的傳遞,如A依賴B,B依賴C。正常使用項目B時的寫法:
dependencies {
compile 'com.xxx.xxx.xxx:1.0.0'
}
但如果只想依賴B,而不依賴C,不傳遞依賴,寫法爲:
dependencies {
compile 'com.xxx.xxx.xxx:1.0.0@aar'
}
另外可以使用exclude module排除一個庫中引用的其他庫。
dependencies {
compile ('com.xxx.xxx.aaa:1.0.0') {
exclude module:'com.xxx.xxx.bbb:1.0.0'
exclude module:'com.xxx.xxx.ccc:1.0.0'
}
}
這樣可以在A庫中去除B庫和C庫的依賴。
Gradle依賴統一管理
Gradle引用依賴非常簡單,但一旦涉及多module,每個module的依賴管理就變得非常複雜,使用Gradle全局變量就可以方便的實現管理。
在根目錄的build.gradle腳本中配置如下代碼:
ext {
android = [compileSdkVersion:23,
buildToolsVersion:'23.0.2']
dependencies = [supportv7:'com.android.support:appcompat-v7:23.2.0']
}
在每個module中,可以通過代碼使用全局的依賴配置:
android {
comlileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion
}
dependencies {
compile rootProject.ext.dependencies.supportv7
}
當然可以直接在根目錄下創建一個config.gradle文件,添加如下代碼:
ext {
android = [compileSdkVersion:23,
buildToolsVersion:'23.0.2']
dependencies = [supportv7:'com.android.support:appcompat-v7:23.2.0']
}
在根目錄的build.gradle文件中添加:
apply from:'config.gradle'
這樣就可以在所有的子module中使用這些參數了,使用方法同上。