1. 基本概念
- Project:Gradle 构建的基本单位,通常对应一个工程。
- Task:Gradle 构建的操作单位,用于执行具体的构建任务,如编译、打包等。
- Build Script:Gradle 构建脚本,使用 Groovy 或 Kotlin DSL 编写,用于配置构建过程。
- Plugin:Gradle 插件,用于扩展构建功能和简化构建配置。
2. 项目结构
在 Android 项目中,通常有三个 Gradle 构建脚本:
Project
app
build.gradle
(模块级)
gradle
wrapper
gradle-wrapper.jar
gradle-wrapper.properties
build.gradle
(项目级)settings.gradle
(项目配置)
2.1 settings.gradle
项目配置
主module配置
// settings.gradle
include ':app'
多个module配置
// 目录结构
-project
-app
-module
-module1
-module2
// settings.gradle
include ":app"
include ':module:module1'
include ':module:module2'
2.2 build.gradle
项目级构建脚本
项目级 build.gradle
文件主要用于配置整个项目的构建设置。
buildscript {
repositories {
mavenLocal()
google()
jcenter()
maven {
allowInsecureProtocol = true // gradle 7及以上使用http仓库时,需要设置这个属性为true
url "http://mvnrepo.alibaba-inc.com/mvn/repository"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.1'
}
}
allprojects {
repositories {
mavenLocal()
google()
jcenter()
maven {
allowInsecureProtocol = true
url "http://mvnrepo.alibaba-inc.com/mvn/repository"
}
}
}
buildscript
:配置构建脚本的依赖,如 Android Gradle 插件。repositories
:配置依赖库的仓库,如 Google Maven 仓库和 JCenter 仓库。allprojects
:配置所有子项目(模块)的设置,这些设置将应用于所有子项目。task
:定义自定义任务,如clean
任务用于删除项目的构建输出。
2.3 gradle-wrapper.properties
gradle
包装器,使我们在没有安装gradle的情况下使用gradle,并且封装了调用方式,在gradle版本变化时可以无感知升级,和Android gradle plugin有对应关系
#Thu Sep 08 11:25:03 CST 2022
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=http://mtl-gradle-mirror.oss-cn-hangzhou.aliyuncs.com/gradle-6.4-bin.zip
2.4 build.gradle
模块级构建脚本
模块级 build.gradle
文件主要用于配置模块的构建设置。
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
apply plugin
:应用 Android Gradle 插件。android
:配置 Android 构建设置,如 SDK 版本、应用 ID、版本号等。defaultConfig
:配置默认的构建变体设置。buildTypes
:配置不同的构建类型,如 debug 和 release。dependencies
:配置模块的依赖库。
3. 常用命令
./gradlew tasks
: 查看所有任务./gradlew androidDependencies
: 查看依赖库./gradlew signingReport
: 查看签名文件信息./gradlew assemble
: 编译并打包所有构建变体的 APK 文件./gradlew build
: 构建项目./gradlew assembleDebug
: 编译并打包 debug 构建变体的 APK 文件./gradlew installDebug
: 编译、打包并安装 debug 构建变体的 APK 文件./gradlew clean
: 清除项目的构建输出./gradlew uninstallAll
: 卸载所有APK./gradlew uninstallDebug
: 卸载debug APK