一、Gradle 概述
Gradle 是一个基于 Groovy/Kotlin DSL 的高级构建工具,专为多项目构建和大规模自动化设计。核心特点:
- 基于约定而非配置:提供合理的默认值
- 声明式构建:DSL 描述构建逻辑
- 增量构建:只重建变化的部分
- 依赖管理:强大的依赖解决能力
- 多项目支持:复杂的项目层次结构
- 可扩展性:通过自定义任务和插件扩展
二、核心配置文件
1. settings.gradle
项目设置文件,定义项目结构和全局配置:
groovy
// 包含的子项目
include ':app', ':core', ':feature'
// 指定根项目名称
rootProject.name = 'MyApplication'
// 自定义构建缓存配置
buildCache {
local {
directory = new File(rootDir, 'build-cache')
removeUnusedEntriesAfterDays = 30
}
}
// 插件管理器配置
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
resolutionStrategy {
eachPlugin {
if (requested.id.id == 'com.android.application') {
useModule("com.android.tools.build:gradle:${requested.version}")
}
}
}
}
2. build.gradle
(Project-Level)
项目级构建配置:
groovy
// 子项目通用配置
subprojects {
apply plugin: 'java'
repositories {
mavenCentral()
google()
}
dependencies {
testImplementation 'junit:junit:4.13.2'
}
}
// 构建脚本依赖
buildscript {
ext {
// 统一版本管理
kotlin_version = '1.7.10'
hilt_version = '2.42'
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.3.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
}
}
// 自定义任务
task clean(type: Delete) {
delete rootProject.buildDir
}
task generateBuildReport {
doLast {
def report = new File("$buildDir/build-report.md")
report.text = """
# Build Report
- Project: $project.name
- Version: ${project.version ?: '1.0.0'}
- Build Time: ${new Date()}
"""
}
}
3. build.gradle
(Module-Level)
模块级构建配置(以 Android 为例):
groovy
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
android {
// 编译和目标SDK配置
compileSdk 33
// 默认配置
defaultConfig {
applicationId "com.example.myapp"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// 自定义变量
buildConfigField "String", "API_KEY", "\"${System.env.API_KEY}\""
resValue "string", "app_name", "My App"
}
// 构建类型
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
// 签名配置
signingConfig signingConfigs.release
}
debug {
applicationIdSuffix ".debug"
versionNameSuffix "-debug"
debuggable true
}
}
// 编译选项
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
// 增量注解处理
incremental true
}
kotlinOptions {
jvmTarget = '11'
freeCompilerArgs += ["-Xjvm-default=all"]
}
// 产品变种
flavorDimensions "version"
productFlavors {
free {
dimension "version"
applicationIdSuffix ".free"
}
pro {
dimension "version"
applicationIdSuffix ".pro"
}
}
// 构建特性
buildFeatures {
viewBinding true
compose true
}
// Compose 选项
composeOptions {
kotlinCompilerExtensionVersion '1.3.0'
}
// 源集配置
sourceSets {
main {
java.srcDirs += 'src/main/kotlin'
res.srcDirs += ['src/main/res', 'src/main/theme']
}
androidTest {
java.srcDirs += 'src/androidTest/kotlin'
}
}
}
// 依赖配置
dependencies {
// 标准依赖项
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.5.1'
// Kotlin 标准库
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
// Android KTX
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.6.0-alpha02"
// Compose 依赖
implementation "androidx.compose.ui:ui:1.3.0-rc01"
// Hilt 依赖注入
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-compiler:$hilt_version"
// 模块依赖
implementation project(':core')
// 变种特定依赖
freeImplementation 'com.google.android.gms:play-services-ads:21.2.0'
// 测试依赖
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
// 调试工具
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.9.1'
}
// 自定义配置
configurations {
// 自定义配置
all*.exclude group: 'com.google.guava', module: 'listenablefuture'
// 依赖解析策略
implementation {
resolutionStrategy {
force 'org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.7.10'
cacheDynamicVersionsFor 10, 'minutes'
cacheChangingModulesFor 4, 'hours'
}
}
}
// 自定义任务
task installRelease(type: Exec) {
dependsOn 'assembleRelease'
commandLine 'adb', 'install', '-r', "$buildDir/outputs/apk/release/app-release.apk"
}
// 扩展属性
ext {
apiBaseUrl = "\"https://api.example.com/v1/\""
}
4. gradle.properties
全局 Gradle 属性配置:
properties
# JVM 配置
org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=1024m -Dfile.encoding=UTF-8
# 性能优化
org.gradle.parallel=true
org.gradle.daemon=true
org.gradle.caching=true
android.useAndroidX=true
android.enableJetifier=true
kotlin.incremental=true
# 构建优化
android.kotlin.incremental=true
android.enableR8=true
android.disableResPlaceholders=true
# 自定义属性
versionMajor=1
versionMinor=2
versionPatch=3
sdkVersion=33
# 启用配置缓存
org.gradle.unsafe.configuration-cache=true
三、核心配置属性详解
1. android
配置块
- compileSdkVersion :编译 API 版本(推荐使用
compileSdk
简写) - minSdkVersion:最低支持的 API 级别
- targetSdkVersion:目标 API 级别
- buildToolsVersion:构建工具版本(已弃用)
- namespace:XML 命名空间(AGP 7.0+)
- compileOptions:Java 编译选项
- kotlinOptions:Kotlin 编译选项
- buildFeatures:开启视图绑定、数据绑定等特性
- packagingOptions:APK/AAB 打包配置
- signingConfigs:签名配置
- lintOptions:Lint 检查配置
2. 依赖配置详解
依赖作用域 | 描述 | 使用场景 |
---|---|---|
implementation |
主代码依赖 | 默认依赖方式 |
api |
暴露依赖给其他模块 | 库模块公开API |
compileOnly |
仅编译期有效 | 注解处理 |
runtimeOnly |
仅运行期有效 | 数据库驱动 |
kapt |
Kotlin 注解处理器 | Dagger/Hilt |
annotationProcessor |
Java 注解处理器 | ButterKnife |
testImplementation |
单元测试依赖 | JUnit/Mockito |
androidTestImplementation |
仪器测试依赖 | Espresso/UIAutomator |
debugImplementation |
Debug 构建依赖 | LeakCanary |
releaseImplementation |
Release 构建依赖 | 优化工具 |
3. 构建优化配置
properties
# gradle.properties
# 开启守护进程
org.gradle.daemon=true
# 开启并行构建
org.gradle.parallel=true
# 配置缓存
org.gradle.unsafe.configuration-cache=true
# 增量注解处理
kapt.incremental.apt=true
# R8优化
android.enableR8=true
4. 变体维度配置
groovy
android {
flavorDimensions "version", "environment"
productFlavors {
free {
dimension "version"
}
pro {
dimension "version"
}
staging {
dimension "environment"
}
production {
dimension "environment"
}
}
}
生成构建变体组合:
- freeStagingDebug
- freeStagingRelease
- freeProductionDebug
- freeProductionRelease
- proStagingDebug
- etc.
四、高级配置技巧
1. 统一依赖版本管理
在项目级 build.gradle
:
groovy
// 定义依赖版本
ext {
versions = [
androidx_core: "1.9.0",
androidx_lifecycle: "2.6.0-alpha02",
hilt: "2.44"
]
libraries = [
androidx_core_ktx: "androidx.core:core-ktx:$versions.androidx_core",
lifecycle_viewmodel: "androidx.lifecycle:lifecycle-viewmodel-ktx:$versions.androidx_lifecycle",
hilt_android: "com.google.dagger:hilt-android:$versions.hilt"
]
}
在模块级 build.gradle
:
groovy
dependencies {
implementation rootProject.libraries.androidx_core_ktx
implementation rootProject.libraries.lifecycle_viewmodel
implementation rootProject.libraries.hilt_android
}
2. 自定义构建任务
groovy
// 计算构建时间
task buildTime {
doLast {
def start = System.currentTimeMillis()
tasks.whenTaskAdded { task ->
if (task.name == 'assembleDebug') {
task.doLast {
def end = System.currentTimeMillis()
println "Build took: ${(end - start)/1000} seconds"
}
}
}
}
}
// 动态生成版本信息
task generateVersionInfo {
doLast {
def versionFile = new File("$buildDir/version-info.txt")
versionFile.text = """
Application: $project.name
Version: ${android.defaultConfig.versionName} (${android.defaultConfig.versionCode})
Build Time: ${new Date()}
Git Commit: ${'git rev-parse --short HEAD'.execute().text.trim()}
Kotlin Version: ${KotlinVersion.CURRENT}
"""
}
}
preBuild.dependsOn generateVersionInfo
3. 签名配置安全化
在 ~/.gradle/gradle.properties
(全局属性文件):
properties
RELEASE_STORE_FILE=your/path/app.jks
RELEASE_STORE_PASSWORD=your_keystore_pass
RELEASE_KEY_ALIAS=your_alias
RELEASE_KEY_PASSWORD=your_key_pass
在模块级 build.gradle
:
groovy
signingConfigs {
release {
storeFile file(System.getenv("STORE_FILE") ?: RELEASE_STORE_FILE)
storePassword System.getenv("STORE_PASSWORD") ?: RELEASE_STORE_PASSWORD
keyAlias System.getenv("KEY_ALIAS") ?: RELEASE_KEY_ALIAS
keyPassword System.getenv("KEY_PASSWORD") ?: RELEASE_KEY_PASSWORD
}
}
4. 自定义构建逻辑
groovy
android.applicationVariants.all { variant ->
// 自动重命名APK
variant.outputs.all { output ->
def formattedDate = new Date().format('yyyyMMdd_HHmm')
output.outputFileName = "${variant.flavorName}-${variant.buildType.name}_v${variant.versionName}_${formattedDate}.apk"
}
// 自动上传到Firebase
def firebaseTask = tasks.register("uploadToFirebase${variant.name.capitalize()}") {
dependsOn "assemble${variant.name.capitalize()}"
doLast {
def apkFile = variant.outputs.first().outputFile
exec {
commandLine 'curl', '-X', 'POST',
'https://firebase-api.com/upload',
'-F', "file=@${apkFile}"
}
}
}
// 构建后自动清理临时文件
tasks.named("assemble${variant.name.capitalize()}").configure {
finalizedBy tasks.register("cleanAfter${it.name.capitalize()}") {
doLast {
delete fileTree(dir: 'build/intermediates', include: '**/*.tmp')
}
}
}
}
五、常见问题和最佳实践
1. 性能优化策略
- 配置缓存 :在
gradle.properties
中启用org.gradle.unsafe.configuration-cache=true
- 并行构建 :启用
org.gradle.parallel=true
- 按需配置 :使用
register()
替代create()
延迟创建任务 - 避免配置阶段IO:将文件操作转移到执行阶段
- 增量注解处理 :启用
kapt.use.worker.api=true
2. 依赖冲突解决
groovy
configurations.all {
// 强制使用指定版本
resolutionStrategy.force 'com.google.code.gson:gson:2.9.0'
// 排除指定依赖
exclude group: 'com.android.support', module: 'support-annotations'
// 优先使用最新版本
resolutionStrategy.capabilitiesResolution.withCapability('com.google.guava:listenablefuture') {
selectHighestVersion()
}
// 动态版本缓存策略
resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
}
3. 环境变量管理
groovy
// 获取环境变量
def getApiKey() {
def envKey = System.getenv("API_KEY")
if (envKey != null) return envKey
def props = new Properties()
file("local.properties").withInputStream { props.load(it) }
return props.getProperty("api.key", "")
}
android {
defaultConfig {
buildConfigField "String", "API_KEY", ""${getApiKey()}""
}
}
4. 多模块配置共享
在根目录 common.gradle
:
groovy
ext.configureAndroidModule = { project ->
project.with {
android {
compileSdk 33
defaultConfig {
minSdk 21
targetSdk 33
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.9.0'
}
}
}
在子模块中使用:
groovy
plugins {
id 'com.android.library'
id 'org.jetbrains.kotlin.android'
}
apply from: "$rootDir/common.gradle"
configureAndroidModule(project)
六、Gradle Wrapper 配置
gradle-wrapper.properties
文件配置:
properties
# Gradle 发行版类型 (bin 不包含源码,all 包含)
distributionUrl=https://services.gradle.org/distributions/gradle-7.5-bin.zip
# 解压后存放位置
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
# 下载位置
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
命令行选项:
bash
# 强制刷新依赖
./gradlew --refresh-dependencies
# 并行构建并配置守护进程
./gradlew --parallel --daemon assemble
# 使用特定Gradle版本
./gradlew wrapper --gradle-version 7.5
# 扫描构建性能
./gradlew build --scan
掌握这些核心配置和高级技巧,你将能够构建高效、可维护的 Gradle 项目,大幅提升构建性能和开发效率。