文章目錄
- 變量定義
- 函數定義
- 函數調用
- 閉包參數
- APK輸出配置
- 多channel配置
- 依賴配置
- 關鍵總結
- 常見混淆點
- groovy高度兼容java
變量定義
def debugCdnUrl = "\"http://xxx\""
函數定義
def getTime() { return new Date().format("yyyyMMdd", TimeZone.getDefault())
}
函數調用
apply plugin: 'com.android.application'
println "hello world" signingConfigs { debug { storeFile file('..\\myKey\\xxxKey.jks') keyPassword '123456' }
}buildTypes { debug { signingConfig signingConfigs.debug minifyEnabled false buildConfigField("String", "app_key", "\"${app_key}\"") }
}
閉包參數
android { compileSdkVersion 30 buildToolsVersion '28.0.3' useLibrary 'org.apache.http.legacy' defaultConfig { applicationId "com.jy.demo" minSdkVersion 21 targetSdkVersion 30 }sourceSets { main { jniLibs.srcDir 'libs' }}
}
APK輸出配置
applicationVariants.all { variant -> def buildType = variant.buildType.name variant.getPackageApplicationProvider().get().outputDirectory = ... variant.outputs.each { it.outputFileName = ... }
}
多channel配置
flavorDimensions "channel", 'cdn'
productFlavors { p_xxx { dimension "channel" applicationId "com.xxx.demo" buildConfigField "String", "apkUpdateUrl", '"..."' }
}
依賴配置
dependencies { p_xxxImplementation fileTree(...) p_pftestImplementation fileTree(include: ['*.jar', '*.aar'], dir: 'gamelibs') implementation 'androidx.appcompat:appcompat:1.3.1'
}
關鍵總結
- 方法調用:Groovy 允許省略括號,例如 compileSdkVersion 30 等價于 compileSdkVersion(30)
- 閉包參數:類似 android { … } 的結構,android 是方法,后面的 { … } 是閉包參數
- 屬性賦值:當代碼直接形如 key = value 時(例如 it.outputFileName = …),這是真正的屬性賦值。
- DSL 魔法:Gradle 通過 Groovy 的 methodMissing 和 propertyMissing 機制,將未定義的方法/屬性轉換為配置項。
常見混淆點
groovy高度兼容java
- 在 build.gradle 文件中,可以直接使用 Java 代碼的語法,因為 Groovy(Gradle 的默認 DSL 語言)與 Java 高度兼容。
- 總的來說:可以使用java語法、調用java庫;但是更推薦優先使用groovy語法和gradle的DSL特性。