建立多個 APK

注意:自 2021 年 8 月起,所有新的應用程式都必須以 App Bundle 格式發布。如果您將應用程式發布到 Google Play,請建構並上傳 Android App Bundle。這樣一來,Google Play 就會根據每位使用者的裝置設定,自動產生並提供最佳化的 APK,讓使用者只下載執行應用程式所需的程式碼和資源。如果要發布至不支援 AAB 格式的商店應用程式,建議您發布多個 APK。在此情況下,您必須自行建構、簽署及管理各個 APK。

雖然建議您盡可能建構單一 APK 來支援所有目標裝置,但這可能會因為支援多個 螢幕密度應用程式二進位檔介面 (ABI) 的檔案而產生很大的 APK。縮減 APK 大小的方法之一,就是建立多個 APK,其中包含適用於特定螢幕密度或 ABI 的檔案。

Gradle 可以建立單獨的 APK,其中僅包含每個密度或 ABI 專屬的程式碼和資源。本頁說明如何設定版本以產生多個 APK。如果您需要建立不是根據螢幕密度或 ABI 的不同應用程式版本,請改用建構變數

為多個 APK 設定版本

如要為多個 APK 設定版本,請將 splits 區塊新增至模組層級 build.gradle 檔案。在 splits 區塊中,提供指定您希望 Gradle 如何依密度產生 APK 的 density 區塊,或是指定 Gradle 為每個 ABI 產生 APK 的 abi 區塊。您可以同時提供密度和 ABI 區塊,建構系統會為每個密度和 ABI 組合建立 APK。

針對螢幕密度設定多個 APK

如要針對不同螢幕密度建立獨立的 APK,請在 splits 區塊中新增 density 區塊。在 density 區塊中,提供所需的螢幕密度和相容的螢幕大小清單。只有在每個 APK 資訊清單中需要特定的 <compatible-screens> 元素時,才需要使用相容螢幕大小清單。

下列 Gradle DSL 選項可為螢幕密度設定多個 APK:

Groovy 為 enable,Kotlin 指令碼為 isEnable
如果將此元素設為 true,Gradle 會根據您定義的螢幕密度產生多個 APK。預設值為 false
exclude
指定您不希望 Gradle 產生個別 APK 的密度清單 (以半形逗號分隔)。如果要針對大部分密度產生 APK,但需要排除應用程式不支援的某些密度,請使用 exclude
reset()

清除螢幕密度的預設清單。只有在與 include 元素搭配使用以指定要新增的密度時才會使用。

下列程式碼片段會呼叫 reset() 以清除清單,然後使用 include,將密度清單設為 ldpixxhdpi

reset()                  // Clears the default list from all densities
                         // to no densities.
include "ldpi", "xxhdpi" // Specifies the two densities to generate APKs
                         // for.
include
指定 Gradle 產生 APK 的密度清單 (以半形逗號分隔)。只能與 reset() 搭配使用以指定明確的密度清單。
compatibleScreens

指定相容螢幕大小的清單 (以半形逗號分隔)。這會為每個 APK 插入資訊清單中的 <compatible-screens> 節點。

這項設定可讓您在同一個 build.gradle 區段中,輕鬆管理螢幕密度和螢幕大小。不過,使用 <compatible-screens> 可能會限制應用程式適用的裝置類型。如需支援不同螢幕大小的替代方式,請參閱「螢幕相容性總覽」。

由於每個採用螢幕密度的 APK 都包含 <compatible-screens> 標記,因此對於 APK 支援的螢幕類型設有特定限制,即使您發布了多個 APK,部分新裝置並不符合您的多個 APK 篩選器。因此,Gradle 一律會產生額外的通用 APK,其中包含所有螢幕密度的素材資源,且不會加入 <compatible-screens> 標記。請發布這個通用 APK 以及個別密度的 APK,以便為不符合 APK (含有 <compatible-screens> 標記) 的裝置提供備用選項。

以下範例會為每個螢幕密度產生獨立的 APK,但 ldpixxhdpixxxhdpi 除外。方法是使用 exclude,將這三個密度從所有密度的預設清單中移除。

Groovy

android {
  ...
  splits {

    // Configures multiple APKs based on screen density.
    density {

      // Configures multiple APKs based on screen density.
      enable true

      // Specifies a list of screen densities you don't want Gradle to create multiple APKs for.
      exclude "ldpi", "xxhdpi", "xxxhdpi"

      // Specifies a list of compatible screen size settings for the manifest.
      compatibleScreens 'small', 'normal', 'large', 'xlarge'
    }
  }
}

Kotlin

android {
    ...
    splits {

        // Configures multiple APKs based on screen density.
        density {

            // Configures multiple APKs based on screen density.
            isEnable = true

            // Specifies a list of screen densities you don't want Gradle to create multiple APKs for.
            exclude("ldpi", "xxhdpi", "xxxhdpi")

            // Specifies a list of compatible screen size settings for the manifest.
            compatibleScreens("small", "normal", "large", "xlarge")
        }
    }
}

如要進一步瞭解如何針對特定螢幕類型和裝置自訂應用程式的不同建構變化版本,請參閱「宣告僅支援部分螢幕尺寸」。

為 ABI 設定多個 APK

如要針對不同的 ABI 建立個別的 APK,請在 splits 區塊中新增 abi 區塊。在 abi 區塊中,提供所需的 ABI 清單。

下列 Gradle DSL 選項可為每個 ABI 設定多個 APK:

enable 代表 Groovy,isEnable 適用於 Kotlin 指令碼
如果將此元素設為 true,Gradle 會根據您定義的 ABI 產生多個 APK。預設值為 false
exclude
指定您不希望 Gradle 產生個別 APK 的 ABI 清單 (以半形逗號分隔)。如果要為大部分 ABI 產生 APK,但需要排除應用程式不支援的某些 ABI,請使用 exclude
reset()

清除 ABI 的預設清單。只有在與 include 元素合併使用以指定您要新增的 ABI 時才能使用。

下列程式碼片段會呼叫 reset() 以清除清單並使用 include,將 ABI 清單設為 x86x86_64

reset()                 // Clears the default list from all ABIs to no ABIs.
include "x86", "x86_64" // Specifies the two ABIs we want to generate APKs for.
include
指定您要 Gradle 產生 APK 的 ABI 清單 (以半形逗號分隔)。只有在與 reset() 搭配使用以指定明確的 ABI 清單時才能使用。
universalApk 代表 Groovy,isUniversalApk 適用於 Kotlin 指令碼

如果設為 true,Gradle 不僅會產生個別 ABI 的 APK,還會產生通用 APK。通用 APK 包含單一 APK 中所有 ABI 的程式碼和資源。預設值為 false

請注意,這個選項僅適用於 splits.abi 區塊。根據螢幕密度建構多個 APK 時,Gradle 一律會產生通用 APK,其中包含所有螢幕密度適用的程式碼和資源。

下列範例會為每個 ABI 產生單獨的 APK:x86x86_64。方法是使用 reset() 從 ABI 的空白清單開始,後面接著 include,並提供每個會取得 APK 的 ABI 清單。

Groovy

android {
  ...
  splits {

    // Configures multiple APKs based on ABI.
    abi {

      // Enables building multiple APKs per ABI.
      enable true

      // By default all ABIs are included, so use reset() and include to specify that you only
      // want APKs for x86 and x86_64.

      // Resets the list of ABIs for Gradle to create APKs for to none.
      reset()

      // Specifies a list of ABIs for Gradle to create APKs for.
      include "x86", "x86_64"

      // Specifies that you don't want to also generate a universal APK that includes all ABIs.
      universalApk false
    }
  }
}

Kotlin

android {
  ...
  splits {

    // Configures multiple APKs based on ABI.
    abi {

      // Enables building multiple APKs per ABI.
      isEnable = true

      // By default all ABIs are included, so use reset() and include to specify that you only
      // want APKs for x86 and x86_64.

      // Resets the list of ABIs for Gradle to create APKs for to none.
      reset()

      // Specifies a list of ABIs for Gradle to create APKs for.
      include("x86", "x86_64")

      // Specifies that you don't want to also generate a universal APK that includes all ABIs.
      isUniversalApk = false
    }
  }
}

如需支援的 ABI 清單,請參閱「支援的 ABI」。

不含原生/C++ 程式碼的專案

如果專案沒有原生/C++ 程式碼,「Build Variants」面板會有兩個資料欄:「Module」和「Active Build Variant」,如圖 1 所示。

「Build Variant」面板
圖 1.「Build Variants」面板會為沒有原生/C++ 程式碼的專案提供兩個資料欄。

模組的「Active Build Variant」值會決定已部署並在編輯器中顯示的建構變數。如要切換變化版本,請按一下模組的「Active Build Variant」儲存格,然後從清單欄位中選擇所需變數。

含有原生/C++ 程式碼的專案

如果專案含有原生/C++ 程式碼,「Build Variants」面板會包含三個資料欄:「Module」、「Active Build Variant」和「Active ABI」,如圖 2 所示。

圖 2:「Build Variants」面板會為含有原生/C++ 程式碼的專案新增「Active ABI」欄。

模組的「Active Build Variant」值會決定已部署且顯示在編輯器中的建構變數。以原生模組來說,「Active ABI」值會決定編輯器使用的 ABI,但不會影響部署的內容。

如要變更建構類型或 ABI:

  1. 按一下「Active Build Variant」或「Active ABI」欄的儲存格。
  2. 從清單欄位中選擇所需的變數或 ABI。系統會自動執行新的同步作業。

變更應用程式或資料庫模組的任一資料欄後,該變更會套用至所有從屬資料列。

設定版本管理

Gradle 產生多個 APK 時,每個 APK 預設都有相同的版本資訊,如模組層級 build.gradlebuild.gradle.kts 檔案所指定。由於 Google Play 商店不允許同一個應用程式提供多個 APK,且每個 APK 都具有相同的版本資訊,因此上傳至 Play 商店前,您必須確保每個 APK 都有專屬的 versionCode

您可以將模組層級的 build.gradle 檔案覆寫每個 APK 的 versionCode。透過建立對應,為設定多個 APK 的每個 ABI 和密度指派專屬的數值,您可以將 defaultConfigproductFlavors 區塊中定義的版本代碼與指派給密度或 ABI 的數值結合,藉此覆寫輸出版本代碼。

在以下範例中,x86 ABI 的 APK 取得 2004 的 versionCodex86_64 ABI 則會取得 3004 的 versionCode

以大規模的方式指派版本代碼 (例如 1000),之後當您需要更新應用程式時,可以指派專屬的版本代碼。舉例來說,如果 defaultConfig.versionCode 在後續更新時疊代至 5,Gradle 會將 2005 的 versionCode 指派給 x86 APK,並將 3005 指派給 x86_64 APK。

提示:如果您的版本包含通用 APK,請為其指派一個低於任何其他 APK 的 versionCode。由於 Google Play 商店會安裝與目標裝置相容的應用程式版本,並具有最高的 versionCode,因此將較低的 versionCode 指派給通用 APK 可確保 Google Play 商店會先嘗試安裝其中一個 APK,然後才退回使用通用 APK。下列程式碼範例處理此問題,不會覆寫通用 APK 的預設 versionCode

Groovy

android {
  ...
  defaultConfig {
    ...
    versionCode 4
  }
  splits {
    ...
  }
}

// Map for the version code that gives each ABI a value.
ext.abiCodes = ['armeabi-v7a':1, x86:2, x86_64:3]

// For per-density APKs, create a similar map:
// ext.densityCodes = ['mdpi': 1, 'hdpi': 2, 'xhdpi': 3]

import com.android.build.OutputFile

// For each APK output variant, override versionCode with a combination of
// ext.abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
android.applicationVariants.all { variant ->

  // Assigns a different version code for each output APK
  // other than the universal APK.
  variant.outputs.each { output ->

    // Stores the value of ext.abiCodes that is associated with the ABI for this variant.
    def baseAbiVersionCode =
            // Determines the ABI for this variant and returns the mapped value.
            project.ext.abiCodes.get(output.getFilter(OutputFile.ABI))

    // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
    // the following code doesn't override the version code for universal APKs.
    // However, because you want universal APKs to have the lowest version code,
    // this outcome is desirable.
    if (baseAbiVersionCode != null) {

      // Assigns the new version code to versionCodeOverride, which changes the
      // version code for only the output APK, not for the variant itself. Skipping
      // this step causes Gradle to use the value of variant.versionCode for the APK.
      output.versionCodeOverride =
              baseAbiVersionCode * 1000 + variant.versionCode
    }
  }
}

Kotlin

android {
  ...
  defaultConfig {
    ...
    versionCode = 4
  }
  splits {
    ...
  }
}

// Map for the version code that gives each ABI a value.
val abiCodes = mapOf("armeabi-v7a" to 1, "x86" to 2, "x86_64" to 3)

// For per-density APKs, create a similar map:
// val densityCodes = mapOf("mdpi" to 1, "hdpi" to 2, "xhdpi" to 3)

import com.android.build.api.variant.FilterConfiguration.FilterType.*

// For each APK output variant, override versionCode with a combination of
// abiCodes * 1000 + variant.versionCode. In this example, variant.versionCode
// is equal to defaultConfig.versionCode. If you configure product flavors that
// define their own versionCode, variant.versionCode uses that value instead.
androidComponents {
    onVariants { variant ->

        // Assigns a different version code for each output APK
        // other than the universal APK.
        variant.outputs.forEach { output ->
            val name = output.filters.find { it.filterType == ABI }?.identifier

            // Stores the value of abiCodes that is associated with the ABI for this variant.
            val baseAbiCode = abiCodes[name]
            // Because abiCodes.get() returns null for ABIs that are not mapped by ext.abiCodes,
            // the following code doesn't override the version code for universal APKs.
            // However, because you want universal APKs to have the lowest version code,
            // this outcome is desirable.
            if (baseAbiCode != null) {
                // Assigns the new version code to output.versionCode, which changes the version code
                // for only the output APK, not for the variant itself.
                output.versionCode.set(baseAbiCode * 1000 + (output.versionCode.get() ?: 0))
            }
        }
    }
}

如要更多替代版本代碼配置的範例,請參閱「指派版本代碼」。

建立多個 APK

設定模組層級的 build.gradlebuild.gradle.kts 檔案以建構多個 APK 後,請依序點選「Build」>「Build APK」,為「Project」窗格中目前所選模組建構所有 APK。Gradle 會在專案的 build/outputs/apk/ 目錄中,為每個密度或 ABI 建立 APK。

Gradle 會針對您設定的多個 APK 的每個密度或 ABI 建構一個 APK。如果您為密度和 ABI 啟用多個 APK,Gradle 會為每個密度和 ABI 組合建立 APK。

舉例來說,下列 build.gradle 程式碼片段可讓您針對 mdpihdpi 密度建構多個 APK,以及 x86x86_64 ABI:

Groovy

...
  splits {
    density {
      enable true
      reset()
      include "mdpi", "hdpi"
    }
    abi {
      enable true
      reset()
      include "x86", "x86_64"
    }
  }

Kotlin

...
  splits {
    density {
      isEnable = true
      reset()
      include("mdpi", "hdpi")
    }
    abi {
      isEnable = true
      reset()
      include("x86", "x86_64")
    }
  }

範例設定中的輸出內容含有以下 4 個 APK:

  • app-hdpiX86-release.apk:包含 hdpi 密度和 x86 ABI 的程式碼和資源。
  • app-hdpiX86_64-release.apk:包含 hdpi 密度和 x86_64 ABI 的程式碼和資源。
  • app-mdpiX86-release.apk:包含 mdpi 密度和 x86 ABI 的程式碼和資源。
  • app-mdpiX86_64-release.apk:包含 mdpi 密度和 x86_64 ABI 的程式碼和資源。

根據螢幕密度建構多個 APK 時,除了個別密度 APK 以外,Gradle 一律會產生通用 APK,其中包含所有密度適用的程式碼和資源。

根據 ABI 建構多個 APK 時,如果您在 build.gradle 檔案的 splits.abi 區塊 (適用於 Groovy) 或 build.gradle.kts 檔案 (適用於 Kotlin 指令碼) 的 splits.abi 區塊中指定 universalApk true,Gradle 只會產生包含所有 ABI 程式碼和資源的 APK。isUniversalApk = true

APK 檔案名稱格式

建構多個 APK 時,Gradle 會使用以下配置產生 APK 檔案名稱:

modulename-screendensityABI-buildvariant.apk

配置元件如下:

modulename
指定正在建構的模組名稱。
screendensity
如果已啟用多個適用於螢幕密度的 APK,請指定 APK 的螢幕密度,例如 mdpi
ABI

如果啟用多個 ABI 的 APK,請指定 APK 的 ABI,例如 x86

如果同時啟用多個螢幕密度和 ABI 的 APK,Gradle 會將密度名稱與 ABI 名稱串連,例如 mdpiX86。如果為個別 ABI APK 啟用 universalApk,Gradle 會使用 universal 做為通用 APK 檔案名稱的 ABI 部分。

buildvariant
指定目前建構的建構變數,例如 debug

舉例來說,為 myApp 偵錯版本建構 mdpi 螢幕密度 APK 時,APK 檔案名稱為 myApp-mdpi-debug.apk。針對 mdpi 螢幕密度和 x86 ABI 建構多個 APK 的 myApp 發布版本,其 APK 檔案名稱為 myApp-mdpiX86-release.apk