文章目录
 - 变量定义
 - 函数定义
 - 函数调用
 - 闭包参数
 - 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特性。