1、gradle.properties中定义变量全局可用,可在任何*.gradle中直接使用
// 定义在 gradle.properties
gradlePropertyKey="gradlePropertyValue"
// 在任何project或者module的.gradle文件中都可直接访问
print(gradlePropertyKey)
2、在根目录下的build.gradle中设置变量
// 在project的build.gradle中定义变量、这里我用的是gradle-8.7
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
}
ext {
// 定义全局变量
compileSdkVersion = 33
minSdkVersion = 21
targetSdkVersion = 33
versionCode = 1
versionName = "1.0"
}
// 以下是在module对应的build.gradle中引用
println(rootProject.ext.compileSdkVersion)
println(rootProject.ext.minSdkVersion)
println(rootProject.ext.versionName)
3、在module的build.gradle中定义变量
// 和 android 块并列
ext {
moduleVersionCode = 211
moduleVersionName = "1.111"
}
// 打印
println(moduleVersionCode)
println(moduleVersionName)
android {
defaultConfig {
versionCode moduleVersionCode
versionName moduleVersionName
}
...
}
4、 新建一个config.gradle
// config.gradle
ext {
compileSdkVersion = 33
minSdkVersion = 21
targetSdkVersion = 33
versionCode = 1
versionName = "1.0"
moduleVersionCode = 2
moduleVersionName = "1.1"
}
// 应用模块的 build.gradle
apply from: '../config.gradle' // 适当调整路径
plugins {
id 'com.android.application'
id 'kotlin-android'
}
// 可以直接使用
android {
compileSdk = compileSdkVersion // 使用引入的变量
defaultConfig {
targetSdk = targetSdkVersion
versionCode = moduleVersionCode // 使用引入的模块变量
versionName = moduleVersionName // 使用引入的模块变量
}
}
当你使用 apply from: '../config.gradle' 引入 config.gradle 文件后,定义在 config.gradle 中的变量会直接在当前模块的 build.gradle 中可用,无需使用 rootProject 进行引用。你可以直接使用这些变量
5、buildConfigField
buildConfigField 是用于在 Android 项目的 build.gradle 中定义构建时常量的功能。这些常量会在生成的 BuildConfig 类中自动可用,通常用于存储与构建相关的配置信息,比如 API 版本、URL、特性开关等。
buildConfigField 可被放置在特定的块中。如 defaultConfig、buildType、productFlavors 等,它不能在 android 块的其他地方使用、 当在 buildConfigField 中定义字符串常量时,字符串的值需要用双引号括起来,并且如果字符串内部包含双引号,则需要使用反斜杠 \ 进行转义
。
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
}
android {
defaultConfig {
buildConfigField "String", "API_URL", "https://www.baidu.com" //添加了API_URL变量
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
buildConfigField "String", "DEBUG", "true"
}
release {
buildConfigField "String", "DEBUG", "false"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}