build.gradle详解

史上最全Android build.gradle配置详解,你懂的!

What is the difference between “sourceCompatibility” and “targetCompatibility”?

Android Studio系列之代码混淆proguardFiles

项目全局 build.gradle

TODO

模块中的 build.gradle

apply 部分

1
2
apply plugin: 'com.android.application' // 表示这是一个应用程序模块
apply plugin: 'com.android.library' // 表示这是一个库模块
  • 应用程序模块:可以直接运行,打包得到.apk文件。
  • 库模块:只能作为代码库依附别的应用程序模块运行,打包得到.aar文件。

android { }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
android {
// 编译使用的 Android 版本
compileSdkVersion 34

// 使用项目全局 build.gradle 指定的版本
compileSdkVersion rootProject.ext.COMPILE_SDK_VERSION

// 编译使用的构建工具的版本
buildToolsVersion XX

defaultConfig {
applicationId "com.saoke.demo" // 项目包名
minSdkVersion 16
targetSdkVersion 27
versionCode 1
versionName "1.0"

// 使用 AndroidJUnitRunner 进行单元测试
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

compileOptions {
// 此处的 sourceCompatibility 和 targetCompatibility 对应 javac 中的 -target release 和 -source release

// 指定用于编译 Java 文件的 Java 版本
sourceCompatibility JavaVersion.VERSION_1_8

// 编译后文件最低兼容的 Java 版本
targetCompatibility JavaVersion.VERSION_1_8
}

buildTypes {
// 生产环境配置
release {
// 开启混淆
minifyEnabled true

// 指定混淆的规则文件
// proguard-android.txt 是 SDK 自带的,我们可以在同目录下的 proguard-rules.pro 中自定义
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

// 在代码中可通过`int versionCode = BuildConfig.VERSION_CODE`访问
// 三个参数分别代表数据类型、键、值
buildConfigField 'int', 'VERSION_CODE', "${rootProject.ext.VERSION_CODE}"
buildConfigField 'String', 'VERSION_NAME', "\"${rootProject.ext.VERSION_NAME}\""
}

debug {
// 同上
}
}
}

Dependencies { }

定义依赖关系。

  • 本地依赖:对本地的 jar 包或目录添加依赖关系
  • 库依赖:对项目中的库模块添加依赖关系
  • 远程依赖:对 Maven、jCener 上的项目添加依赖关系
1
2
3
4
5
6
7
8
9
// 本地依赖,将 libs 目录下所有 .jar 和 .aar 后缀的文件都添加到项目的构建路径当中
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])

// 本地依赖或库依赖
implementation project(':moduleName')

// 远程依赖
implementation 'com.google.android.material:1.0.0'
implementation("com.google.android.material:material:$DEV_VERSION.ANDROIDX_MATERIAL_VERSION")

implementation

implementation引入的依赖参与编译和打包,且是不可传递的,只能在模块内部使用。如A模块依赖了Gson,则B模块无法访问Gson
未使用的依赖不会被打包,因此可以减少编译时间和减少最终APK的大小。

api

compile相同。
参与编译和打包。该依赖方式会传递所依赖的库,当其他模块依赖了该模块时,可以使用该模块下用 api 依赖的库。

compile

在 gradle 3.0 中已弃用,被implementationapi替代。
使用该方式依赖的库会参与编译和打包。

compileOnly

只在编译时有效,不会参与打包。通常用于开发阶段需要但最终打包时不需要的库,如在开发测试工具时,可能需要使用的一些测试相关的库。