gradle配置構建

配置構建

Android 構建系統編譯應用資源和源代碼,然後將它們打包成可供您測試、部署、簽署和分發的 APK。Android Studio 使用 Gradle 這一高級構建工具包來自動化執行和管理構建流程,同時也允許您定義靈活的自定義構建配置。每個構建配置均可自行定義一組代碼和資源,同時對所有應用版本共有的部分加以重複利用。Android Plugin for Gradle 與這個構建工具包協作,共同提供專用於構建和測試 Android 應用的流程和可配置設置。

Gradle 和 Android 插件獨立於 Android Studio 運行。這意味着,您可以在 Android Studio 內、使用計算機上的命令行工具或在未安裝 Android Studio 的計算機(例如持續性集成服務器)上構建 Android 應用。如果您不使用 Android Studio,可以學習如何從命令行構建和運行您的應用。無論您是從命令行、在遠程計算機上還是使用 Android Studio 構建項目,構建的輸出都相同。

注:由於 Gradle 和 Android 插件獨立於 Android Studio 運行,您需要單獨更新構建工具。請閱讀版本說明,瞭解如何更新 Gradle 和 Android 插件。

Android 構建系統非常靈活,讓您能夠在不修改應用核心源文件的情況下執行自定義構建配置。本章幫助您瞭解 Android 構建系統的工作原理,以及它如何幫助您對多個構建配置進行自定義和自動化處理。如果您只想瞭解有關部署應用的更多信息,請參閱在 Android Studio 中構建和運行項目。要立即開始使用 Android Studio 創建自定義構建配置,請參閱配置構建變體。

構建流程


構建流程涉及許多將您的項目轉換成 Android 應用軟件包 (APK) 的工具和流程。構建流程非常靈活,因此瞭解它的一些底層工作原理會很有幫助。

這裏寫圖片描述

圖 1. 典型 Android 應用模塊的構建流程。

如圖 1 所示,典型 Android 應用模塊的構建流程通常依循下列步驟:

  1. 編譯器將您的源代碼轉換成 DEX(Dalvik Executable) 文件(其中包括運行在 Android 設備上的字節碼),將所有其他內容轉換成已編譯資源。
  2. APK 打包器將 DEX 文件和已編譯資源合併成單個 APK。不過,必須先簽署 APK,才能將應用安裝並部署到 Android 設備上。
  3. APK 打包器使用調試或發佈密鑰庫簽署您的 APK:
    a. 如果您構建的是調試版本的應用(即專用於測試和分析的應用),打包器會使用調試密鑰庫簽署您的應用。Android Studio 自動使用調試密鑰庫配置新項目。
    b. 如果您構建的是打算向外發佈的發佈版本應用,打包器會使用發佈密鑰庫簽署您的應用。要創建發佈密鑰庫,請閱讀在 Android Studio 中籤署您的應用。
  4. 在生成最終 APK 之前,打包器會使用 zipalign 工具對應用進行優化,減少其在設備上運行時的內存佔用。

構建流程結束時,您將獲得可用來進行部署、測試的調試 APK,或者可用來發布給外部用戶的發佈 APK。

自定義構建配置


Gradle 和 Android 插件可幫助您完成以下方面的構建配置:

構建類型

構建類型定義 Gradle 在構建和打包您的應用時使用的某些屬性,通常針對開發生命週期的不同階段進行配置。例如,調試構建類型支持調試選項,使用調試密鑰簽署 APK;而發佈構建類型則可壓縮、混淆 APK 以及使用發佈密鑰簽署 APK 進行分發。您必須至少定義一個構建類型才能構建應用 - Android Studio 默認情況下會創建調試和發佈構建類型。要開始爲應用自定義打包設置,請學習如何配置構建類型。

產品風味

    產品風味代表您可以發佈給用戶的不同應用版本,例如免費和付費的應用版本。您可以將產品風味自定義爲使用不同的代碼和資源,同時對所有應用版本共有的部分加以共享和重複利用。產品風味是可選項,並且您必須手動創建。要開始創建不同的應用版本,請學習如何配置產品風味。

構建變體

    構建變體是構建類型與產品風味的交叉產物,是 Gradle 在構建應用時使用的配置。您可以利用構建變體在開發時構建產品風味的調試版本,或者構建已簽署的產品風味發佈版本進行分發。您並不直接配置構建變體,而是配置組成變體的構建類型和產品風味。創建附加構建類型或產品風味也會創建附加構建變體。要了解如何創建和管理構建變體,請閱讀配置構建變體概覽。

清單條目

    您可以爲構建變體配置中清單文件的一些屬性指定值。這些構建值會替換清單文件中的現有值。如果您想爲模塊生成多個 APK,讓每一個 APK 文件都具有不同的應用名稱、最低 SDK 版本或目標 SDK 版本,便可運用這一技巧。存在多個清單時,Gradle 會合並清單設置。

依賴項

    構建系統管理來自您的本地文件系統以及來自遠程存儲區的項目依賴項。這樣一來,您就不必手動搜索、下載依賴項的二進制文件包以及將它們複製到項目目錄內。要了解更多信息,請學習如何聲明依賴項。

簽署

    構建系統讓您能夠在構建配置中指定簽署設置,並可在構建過程中自動簽署您的 APK。構建系統通過使用已知憑據的默認密鑰和證書籤署調試版本,以避免在構建時提示密碼。除非您爲此構建顯式定義簽署配置,否則,構建系統不會簽署發佈版本。如果您沒有發佈密鑰,可以按簽署您的應用中所述生成一個。

ProGuard

    構建系統讓您能夠爲每個構建變體指定不同的 ProGuard 規則文件。構建系統可在構建過程中運行 ProGuard 對類進行壓縮和混淆處理。

APK 拆分

    構建系統讓您能夠自動構建不同的 APK,並且每個 APK 只包含特定屏幕密度或應用二進制界面 (ABI) 所需的代碼和資源。如需瞭解詳細信息,請參閱配置 APK 拆分。

構建配置文件


創建自定義構建配置需要您對一個或多個構建配置文件(或 build.gradle 文件)進行更改。這些純文本文件使用域特定語言 (DSL) 以 Groovy 語言描述和操作構建邏輯,後者是一種適用於 Java 虛擬機 (JVM) 的動態語言。您無需瞭解 Groovy 便可開始配置構建,因爲 Android Plugin for Gradle 引入了您需要的大多數 DSL 元素。如需瞭解有關 Android 插件 DSL 的更多信息,請閱讀 DSL 參考文檔。

開始新項目時,Android Studio 會自動爲您創建其中的部分文件(如圖 2 所示),併爲它們填充合理的默認值。

這裏寫圖片描述

圖 2. Android 應用模塊的默認項目結構。

有幾個 Gradle 構建配置文件是 Android 應用標準項目結構的組成部分。您必須瞭解其中每一個文件的範圍和用途及其應定義的基本 DSL 元素,才能着手配置構建。

Gradle 設置文件

settings.gradle 文件位於項目根目錄,用於指示 Gradle 在構建應用時應將哪些模塊包括在內。對大多數項目而言,該文件很簡單,只包括以下內容:

'include ‘:app’

不過,多模塊項目需要指定應包括在最終構建之中的每個模塊。

頂級構建文件

頂級 build.gradle 文件位於項目根目錄,用於定義適用於項目中所有模塊的構建配置。默認情況下,這個頂級構建文件使用 buildscript {} 代碼塊來定義項目中所有模塊共用的 Gradle 存儲區和依賴項。以下代碼示例描述的默認設置和 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()
   }
}

模塊級構建文件

模塊級 build.gradle 文件位於每個 // 目錄,用於配置適用於其所在模塊的構建設置。您可以通過配置這些構建設置來提供自定義打包選項(例如附加構建類型和產品風味),以及替換 main/ 應用清單或頂級 build.gradle 文件中的設置。

以下這個示例 Android 應用模塊 build.gradle 文件概述了您應該瞭解的部分基本 DSL 元素和設置。



/**
 * 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 構建工具包本身的設置:

gradle.properties

您可以在其中配置項目範圍 Gradle 設置,例如 Gradle 後臺進程的最大堆大小。如需瞭解詳細信息,請參閱構建環境。

local.properties

爲構建系統配置本地環境屬性,例如 SDK 安裝路徑。由於該文件的內容由 Android Studio 自動生成並且專用於本地開發者環境,因此您不應手動修改該文件,或將其納入您的版本控制系統。

將項目與 Gradle 文件同步

當您在項目中對構建配置文件進行更改時,Android Studio 會要求您同步項目文件,以便其導入您的構建配置更改並執行一些檢查來確保您的配置不會造成構建錯誤。

這裏寫圖片描述

圖 3. 在 Android Studio 中將項目與構建配置文件同步。

源集

Android Studio 按邏輯關係將每個模塊的源代碼和資源分組爲源集。模塊的 main/ 源集包括其所有構建變體共用的代碼和資源。其他源集目錄爲可選項,在您配置新的構建變體時,Android Studio 不會自動爲您創建這些目錄。不過,創建類似於 main/ 的源集有助於讓 Gradle 只應在構建特定應用版本時使用的文件和資源井然有序:

src/main/

此源集包括所有構建變體共用的代碼和資源。

src/<buildType>/

創建此源集可加入特定構建類型專用的代碼和資源。

src/<productFlavor>/

創建此源集可加入特定產品風味專用的代碼和資源。

src/<productFlavorBuildType>/

創建此源集可加入特定構建變體專用的代碼和資源。

例如,要生成應用的“完整調試”版本,構建系統需要合併來自以下源集的代碼、設置和資源:

    src/fullDebug/(構建變體源集)
    src/debug/(構建類型源集)
    src/full/(產品風味源集)
    src/main/(主源集)

注:當您在 Android Studio 中使用 File > New 菜單選項新建文件或目錄時,可以針對特定源集進行創建。可供您選擇的源集取決於您的構建配置,如果所需目錄尚不存在,Android Studio 會自動創建。

如果不同源集包含同一文件的不同版本,Gradle 將按以下優先順序決定使用哪一個文件(左側源集替換右側源集的文件和設置):

構建變體 > 構建類型 > 產品風味 > 主源集 > 庫依賴項

這樣一來,Gradle 便可使用專用於您試圖構建的構建變體的文件,同時對與其他應用版本共用的 Activity、應用邏輯和資源加以重複利用。在合併多個清單時,Gradle 使用同一優先順序,這樣每個構建變體都能在最終清單中定義不同的組件或權限。如需瞭解有關創建自定義源集的更多信息,請轉至創建用於構建變體的源集。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章