目前Android Studio創建項目的時候都是依賴於Gradle的,每個項目都有兩個build.gradle,一個是app.gradle另一個是項目gradle。
項目gradle就是用來配置整個項目的基礎資源引用,包括gradle版本的依賴,google、jcenter、阿里雲鏡像之類的庫依賴,類似是這樣:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
//這裏是項目的頂層build.gradle文件,在這裏你可以添加對應的配置項應用於所有的子項目、子module
buildscript {
repositories {
google()
jcenter()
maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
gradle中的每一個標籤都可以通過 ctrl+鼠標左鍵 的方式查看源代碼,我們可以一個個來分析這些標籤是幹啥用的。首先第一個標籤:buildscript
public interface Project extends Comparable<Project>, ExtensionAware, PluginAware {
/** 省略其它代碼 */
/**
* <p>Configures the build script classpath for this project.
*
* <p>The given closure is executed against this project's {@link ScriptHandler}. The {@link ScriptHandler} is
* passed to the closure as the closure's delegate.
*
* @param configureClosure the closure to use to configure the build script classpath.
*/
void buildscript(Closure configureClosure);
}
源代碼中顯示這是一個Project.java文件,非常熟悉吧。實際上整個build.gradle文件可以看作是一個java類,只是它換了一種寫法而已。既然本質上是java,那不就簡單多了嘛。
來看看這段代碼,它與我們樓上展示的那段gradle功能一毛一樣
buildscript {
getRepositories().google()
getRepositories().jcenter()
getRepositories().maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
getRepositories().maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' }
// repositories {
// google()
// jcenter()
// maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
// maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter' }
//
// }
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
有木有發現gradle的小祕密(嘻嘻),repositories其實是buildscript中的一個成員變量(可以這麼理解,但不完全正確),既然是成員變量,那我是不是就可以通過get、set方法去配置或者獲取?沒錯,在gradle中保留這樣的習慣,區別只是寫法不同。set方法改成了類似於java中的“重寫”,get方法倒是與java中的寫法一樣。
比如這個repositories { do something... } 在兩個大括號中間的內容就對repositories的“重寫”,也可以理解爲set方法(畢竟它好像沒有父類,所以這裏說重寫,也只是更方便理解)
與之同理的還有很多不一樣的build標籤,現在瞭解了它的內部原理,以後自己再手動重寫gradle、配置gradle都會變得更輕鬆更香
PS:gradle也可以像java一樣調試輸出,方便我們檢查。使用方法就是這樣:
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
println( "我的天吶->" + getSourceURI())//在任何地方加println都可以輸出
println( "我的天吶" + getDependencies().gradleApi().group)
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
隨後可以在這裏看到自己輸出的日誌