10 KiB
10 KiB
构建系统
目录
Gradle基础
Gradle简介
// Gradle:Android 官方构建工具
// - 基于 Groovy 或 Kotlin DSL
// - 自动化构建
// - 依赖管理
// - 多项目支持
Gradle文件结构
project/
├── build.gradle # 项目级构建配置
├── settings.gradle # 项目设置
└── app/
└── build.gradle # 模块级构建配置
build.gradle (Project)
// Top-level build file
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.0'
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle (Module: app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.app'
compileSdk 33
defaultConfig {
applicationId "com.example.app"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
}
构建配置
Android配置块
android {
// 命名空间
namespace 'com.example.app'
// 编译SDK版本
compileSdk 33
// 默认配置
defaultConfig {
applicationId "com.example.app"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
}
// 构建类型
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
applicationIdSuffix ".debug"
debuggable true
}
}
// 产品变体
productFlavors {
free {
applicationIdSuffix ".free"
versionNameSuffix "-free"
}
paid {
applicationIdSuffix ".paid"
versionNameSuffix "-paid"
}
}
}
签名配置
android {
signingConfigs {
release {
storeFile file('my-release-key.jks')
storePassword 'password'
keyAlias 'my-key-alias'
keyPassword 'password'
}
}
buildTypes {
release {
signingConfig signingConfigs.release
}
}
}
源集配置
android {
sourceSets {
main {
java.srcDirs = ['src/main/java']
res.srcDirs = ['src/main/res']
assets.srcDirs = ['src/main/assets']
}
debug {
java.srcDirs = ['src/debug/java']
res.srcDirs = ['src/debug/res']
}
}
}
依赖管理
依赖类型
dependencies {
// implementation:编译和运行时依赖
implementation 'androidx.appcompat:appcompat:1.6.1'
// api:编译和运行时依赖,并暴露给依赖模块
api 'com.google.guava:guava:31.1-jre'
// compileOnly:仅编译时依赖
compileOnly 'javax.annotation:jsr250-api:1.0'
// runtimeOnly:仅运行时依赖
runtimeOnly 'com.h2database:h2:1.4.200'
// testImplementation:测试依赖
testImplementation 'junit:junit:4.13.2'
// androidTestImplementation:Android测试依赖
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
依赖版本管理
// 在项目级 build.gradle 中定义版本
ext {
appcompatVersion = '1.6.1'
materialVersion = '1.9.0'
}
// 在模块中使用
dependencies {
implementation "androidx.appcompat:appcompat:$appcompatVersion"
implementation "com.google.android.material:material:$materialVersion"
}
依赖排除
dependencies {
implementation('com.example:library:1.0') {
exclude group: 'com.google.guava', module: 'guava'
}
}
本地依赖
dependencies {
// 本地JAR
implementation files('libs/library.jar')
implementation fileTree(dir: 'libs', include: ['*.jar'])
// 本地AAR
implementation(name: 'library', ext: 'aar')
// 本地模块
implementation project(':mylibrary')
}
构建变体
构建类型(Build Types)
android {
buildTypes {
debug {
applicationIdSuffix ".debug"
debuggable true
minifyEnabled false
}
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
staging {
initWith release
applicationIdSuffix ".staging"
debuggable true
}
}
}
产品变体(Product Flavors)
android {
flavorDimensions "version"
productFlavors {
free {
dimension "version"
applicationIdSuffix ".free"
versionNameSuffix "-free"
}
paid {
dimension "version"
applicationIdSuffix ".paid"
versionNameSuffix "-paid"
}
china {
dimension "version"
applicationIdSuffix ".cn"
}
global {
dimension "version"
applicationIdSuffix ".global"
}
}
}
// 构建变体组合:
// freeChinaDebug, freeChinaRelease
// freeGlobalDebug, freeGlobalRelease
// paidChinaDebug, paidChinaRelease
// paidGlobalDebug, paidGlobalRelease
变体特定配置
android {
productFlavors {
free {
// 变体特定资源
resValue "string", "app_name", "MyApp Free"
// 变体特定清单
manifestPlaceholders = [appName: "MyApp Free"]
}
paid {
resValue "string", "app_name", "MyApp Paid"
manifestPlaceholders = [appName: "MyApp Paid"]
}
}
}
构建优化
构建速度优化
// 1. 启用构建缓存
android {
buildCache {
enabled = true
}
}
// 2. 启用并行构建
org.gradle.parallel=true
// 3. 启用守护进程
org.gradle.daemon=true
// 4. 增加内存
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=512m
// 5. 配置增量编译
android {
compileOptions {
incremental = true
}
}
依赖优化
// 1. 使用最新稳定版本
// 2. 避免使用动态版本
// ❌ implementation 'com.example:library:+'
// ✅ implementation 'com.example:library:1.0.0'
// 3. 使用 implementation 而不是 api
// 4. 排除不必要的传递依赖
ProGuard优化
android {
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
// proguard-rules.pro
-keep class com.example.model.** { *; }
-keepclassmembers class * {
@com.example.annotation.Keep *;
}
构建变体优化
// 只构建需要的变体
// 使用 assembleFreeDebug 而不是 assemble
Gradle脚本
自定义任务
// 在 build.gradle 中定义任务
task hello {
doLast {
println 'Hello, Gradle!'
}
}
// 执行任务
// ./gradlew hello
任务依赖
task taskA {
doLast {
println 'Task A'
}
}
task taskB {
dependsOn taskA
doLast {
println 'Task B'
}
}
条件执行
task buildRelease {
doLast {
if (project.hasProperty('release')) {
println 'Building release...'
} else {
println 'Building debug...'
}
}
}
文件操作
task copyFiles {
doLast {
copy {
from 'src/main/assets'
into 'build/assets'
include '*.txt'
}
}
}
常见问题
问题1:Gradle同步慢
// 解决方案:
// 1. 使用国内镜像源
// 在 build.gradle 中配置
repositories {
maven { url 'https://maven.aliyun.com/repository/google' }
maven { url 'https://maven.aliyun.com/repository/central' }
google()
mavenCentral()
}
// 2. 配置 Gradle 代理
// gradle.properties
systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=1080
// 3. 使用本地 Gradle 版本
// File → Settings → Build, Execution, Deployment → Gradle
// 选择 "Use local gradle distribution"
问题2:依赖冲突
// 解决方案:
// 1. 查看依赖树
./gradlew app:dependencies
// 2. 排除冲突依赖
dependencies {
implementation('com.example:library:1.0') {
exclude group: 'com.google.guava', module: 'guava'
}
}
// 3. 强制使用特定版本
configurations.all {
resolutionStrategy {
force 'com.google.guava:guava:31.1-jre'
}
}
问题3:构建失败
// 解决方案:
// 1. 清理项目
./gradlew clean
// 2. 重新构建
./gradlew build
// 3. 检查错误信息
// 查看 Build 窗口的错误信息
// 4. 检查依赖
// 确保所有依赖都正确下载
问题4:内存不足
// 解决方案:
// 1. 增加 Gradle 内存
// gradle.properties
org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=512m
// 2. 启用守护进程
org.gradle.daemon=true
// 3. 启用并行构建
org.gradle.parallel=true
Gradle Wrapper
Wrapper配置
// gradle/wrapper/gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
使用Wrapper
# Windows
gradlew.bat build
# Linux/macOS
./gradlew build
总结
Gradle 是 Android 构建系统的核心。熟练掌握 Gradle 配置可以大大提高构建效率和项目质量。
最后更新:2024年