該文檔適合初入Android的小白,幫助理解Android studio和gradle是怎樣配合編譯源碼、資源文件生成apk!
配置搭建
Android Studio 使用Gradle 這一高級構(gòu)建工具包來自動化執(zhí)行和管理構(gòu)建流程,同時也支持自定義構(gòu)建配置。每個構(gòu)建配置均可自行定義一組代碼和資源,同時對所有應(yīng)用版本共有的部分加以重復(fù)利用。Android Plugin for Gradle 與這個構(gòu)建工具包協(xié)作,共同提供用于構(gòu)建和測試 Android 應(yīng)用的流程和設(shè)置。
Gradle 和 Android 插件獨立于 Android Studio 運行。這表示可以在 Android Studio 內(nèi)、使用計算機上的命令行工具或在未安裝 Android Studio 的計算機(例如持續(xù)性集成服務(wù)器)上構(gòu)建 Android 應(yīng)用。如果您不使用 Android Studio,可以學(xué)習(xí)如何從命令行構(gòu)建和運行您的應(yīng)用。無論您是從命令行、在遠(yuǎn)程計算機上還是使用 Android Studio 構(gòu)建項目,構(gòu)建的輸出都相同。
注:由于 Gradle 和 Android 插件獨立于 Android Studio 運行,您需要單獨更新構(gòu)建工具。請閱讀版本說明,了解如何更新 Gradle 和 Android 插件。
接下來進(jìn)入正題!
構(gòu)建流程

如圖 1 所示,典型 Android 應(yīng)用模塊的構(gòu)建流程通常依循下列步驟:
編譯器將您的源代碼轉(zhuǎn)換成 DEX(Dalvik Executable) 文件(其中包括運行在 Android 設(shè)備上的字節(jié)碼),將所有其他內(nèi)容轉(zhuǎn)換成已編譯資源。
APK 打包器將 DEX 文件和已編譯資源合并成單個 APK。不過,必須先簽署 APK,才能將應(yīng)用安裝并部署到 Android 設(shè)備上。
-
APK 打包器使用調(diào)試或發(fā)布密鑰庫簽署您的 APK:
a. 如果構(gòu)建的是調(diào)試版本的應(yīng)用(即專用于測試和分析的應(yīng)用),打包器會使用調(diào)試密鑰庫簽署您的應(yīng)用。Android Studio 自動使用調(diào)試密鑰庫配置新項目。
b. 如果構(gòu)建的是打算向外發(fā)布的發(fā)布版本應(yīng)用,打包器會使用發(fā)布密鑰庫簽署您的應(yīng)用。要創(chuàng)建發(fā)布密鑰庫,請閱讀在 Android Studio 中簽署您的應(yīng)用。
在生成最終 APK 之前,打包器會使用 zipalign 工具對應(yīng)用進(jìn)行優(yōu)化,減少其在設(shè)備上運行時的內(nèi)存占用。
構(gòu)建流程結(jié)束時,您將獲得可用來進(jìn)行部署、測試的調(diào)試 APK,或者可用來發(fā)布給外部用戶的發(fā)布 APK。
構(gòu)建配置文件
創(chuàng)建自定義構(gòu)建配置需要您對一個或多個構(gòu)建配置文件(或 build.gradle 文件)進(jìn)行更改。這些純文本文件使用域特定語言 (DSL) 以 Groovy 語言描述和操作構(gòu)建邏輯,后者是一種適用于 Java 虛擬機 (JVM) 的動態(tài)語言。您無需了解 Groovy 便可開始配置構(gòu)建,因為 Android Plugin for Gradle 引入了您需要的大多數(shù) DSL 元素。如需了解有關(guān) Android 插件 DSL 的更多信息,請閱讀DSL參考文檔。
開始新項目時,Android Studio 會自動為您創(chuàng)建其中的部分文件(如圖 2 所示),并為它們填充合理的默認(rèn)值。

有幾個 Gradle 構(gòu)建配置文件是 Android 應(yīng)用標(biāo)準(zhǔn)項目結(jié)構(gòu)的組成部分。了解其中每一個文件的范圍和用途及其應(yīng)定義的基本 DSL 元素,才能著手配置構(gòu)建。
Gradle 設(shè)置文件
settings.gradle 文件位于項目根目錄,用于指示 Gradle 在構(gòu)建應(yīng)用時應(yīng)將哪些模塊包括在內(nèi)。對大多數(shù)項目而言,該文件很簡單,只包括以下內(nèi)容:
include ‘:app’
不過,多模塊項目需要指定應(yīng)包括在最終構(gòu)建之中的每個模塊。
頂級構(gòu)建文件
頂級 build.gradle 文件位于項目根目錄,用于定義適用于項目中所有模塊的構(gòu)建配置。默認(rèn)情況下,這個頂級構(gòu)建文件使用 buildscript {} 代碼塊來定義項目中所有模塊共用的 Gradle 存儲區(qū)和依賴項。以下代碼示例描述的默認(rèn)設(shè)置和 DSL 元素可在新建項目后的頂級 build.gradle 文件中找到。
/**
* The buildscript {} block is where you configure the repositories and
* dependencies for Gradle itself--meaning, you should not include dependencies
* for your modules here. For example, this block includes the Android plugin for
* Gradle as a dependency because it provides the additional instructions Gradle
* needs to build Android app modules.
*/
buildscript {
/**
* The repositories {} block configures the repositories Gradle uses to
* search or download the dependencies. Gradle pre-configures support for remote
* repositories such as JCenter, Maven Central, and Ivy. You can also use local
* repositories or define your own remote repositories. The code below defines
* JCenter as the repository Gradle should use to look for its dependencies.
*/
repositories {
jcenter()
}
/**
* The dependencies {} block configures the dependencies Gradle needs to use
* to build your project. The following line adds Android Plugin for Gradle
* version 2.3.3 as a classpath dependency.
*/
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
/**
* The allprojects {} block is where you configure the repositories and
* dependencies used by all modules in your project, such as third-party plugins
* or libraries. Dependencies that are not required by all the modules in the
* project should be configured in module-level build.gradle files. For new
* projects, Android Studio configures JCenter as the default repository, but it
* does not configure any dependencies.
*/
allprojects {
repositories {
jcenter()
}
}
模塊級構(gòu)建文件
模塊級 build.gradle 文件位于每個<project><module>目錄,用于配置適用于其所在模塊的構(gòu)建設(shè)置。您可以通過配置這些構(gòu)建設(shè)置來提供自定義打包選項(例如附加構(gòu)建類型和產(chǎn)品風(fēng)味),以及替換 main/ 應(yīng)用清單或頂級 build.gradle 文件中的設(shè)置。
以下這個示例 Android 應(yīng)用模塊 build.gradle 文件概述了您應(yīng)該了解的部分基本 DSL 元素和設(shè)置。
/**
* The first line in the build configuration applies the Android plugin for
* Gradle to this build and makes the android {} block available to specify
* Android-specific build options.
*/
apply plugin: 'com.android.application'
/**
* The android {} block is where you configure all your Android-specific
* build options.
*/
android {
/**
* compileSdkVersion specifies the Android API level Gradle should use to
* compile your app. This means your app can use the API features included in
* this API level and lower.
* buildToolsVersion specifies the version of the SDK build tools, command-line
* utilities, and compiler that Gradle should use to build your app. You need to
* download the build tools using the SDK Manager.
*/
compileSdkVersion 26
buildToolsVersion "26.0.0"
/**
* The defaultConfig {} block encapsulates default settings and entries for all
* build variants, and can override some attributes in main/AndroidManifest.xml
* dynamically from the build system. You can configure product flavors to override
* these values for different versions of your app.
*/
defaultConfig {
/**
* applicationId uniquely identifies the package for publishing.
* However, your source code should still reference the package name
* defined by the package attribute in the main/AndroidManifest.xml file.
*/
applicationId 'com.example.myapp'
// Defines the minimum API level required to run the app.
minSdkVersion 15
// Specifies the API level used to test the app.
targetSdkVersion 26
// Defines the version number of your app.
versionCode 1
// Defines a user-friendly version name for your app.
versionName "1.0"
}
/**
* The buildTypes {} block is where you can configure multiple build types.
* By default, the build system defines two build types: debug and release. The
* debug build type is not explicitly shown in the default build configuration,
* but it includes debugging tools and is signed with the debug key. The release
* build type applies Proguard settings and is not signed by default.
*/
buildTypes {
/**
* By default, Android Studio configures the release build type to enable code
* shrinking, using minifyEnabled, and specifies the Proguard settings file.
*/
release {
minifyEnabled true // Enables code shrinking for the release build type.
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
/**
* The productFlavors {} block is where you can configure multiple product
* flavors. This allows you to create different versions of your app that can
* override defaultConfig {} with their own settings. Product flavors are
* optional, and the build system does not create them by default. This example
* creates a free and paid product flavor. Each product flavor then specifies
* its own application ID, so that they can exist on the Google Play Store, or
* an Android device, simultaneously.
*/
productFlavors {
free {
applicationId 'com.example.myapp.free'
}
paid {
applicationId 'com.example.myapp.paid'
}
}
/**
* The splits {} block is where you can configure different APK builds that
* each contain only code and resources for a supported screen density or
* ABI. You'll also need to configure your build so that each APK has a
* different versionCode.
*/
splits {
// Screen density split settings
density {
// Enable or disable the density split mechanism
enable false
// Exclude these densities from splits
exclude "ldpi", "tvdpi", "xxxhdpi", "400dpi", "560dpi"
}
}
}
/**
* The dependencies {} block in the module-level build configuration file
* only specifies dependencies required to build the module itself.
*/
dependencies {
compile project(":lib")
compile 'com.android.support:appcompat-v7:25.4.0'
compile fileTree(dir: 'libs', include: ['*.jar'])
}
Gradle 屬性文件
Gradle 還包括兩個屬性文件,位于項目根目錄,可用于指定適用于 Gradle 構(gòu)建工具包本身的設(shè)置:
gradle.properties
可以在其中配置項目范圍 Gradle 設(shè)置,例如 Gradle 后臺進(jìn)程的最大堆大小。
local.properties
為構(gòu)建系統(tǒng)配置本地環(huán)境屬性,例如 SDK 安裝路徑。由于該文件的內(nèi)容由 Android Studio 自動生成并且專用于本地開發(fā)者環(huán)境。