建立多個 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 區塊中,提供 density 區塊,指定 Gradle 如何產生每個密度的 APK,或是指定 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> 標記的裝置提供備用選項。

以下範例會為每種螢幕密度 (ldpixxhdpixxxhdpi 除外) 產生獨立的 APK。方法是使用 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,或適用於 Kotlin 指令碼的 isEnable
如果將這項元素設為 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 清單時才會使用。
Groovy 為 universalApk,Kotlin 指令碼則為 isUniversalApk

如果為 true,除了個別 ABI APK 以外,Gradle 也會產生通用 APK。通用 APK 在單一 APK 中包含所有 ABI 的程式碼和資源。預設值為 false

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

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

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 所示。

「BuildVariant」面板
圖 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,因此上傳至 Play 商店前,請務必確認每個 APK 都有專屬的 versionCode

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

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

以大幅遞增的方式指派版本代碼 (例如 1000) 可讓您在需要更新應用程式時指派專屬的版本代碼。舉例來說,如果 defaultConfig.versionCode 在後續更新中疊代為 5,Gradle 會為 x86 APK 指派 2005 的 versionCode,並將 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 密度,以及 x86x86_64 ABI 建構多個 APK:

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 區塊中指定 isUniversalApk = true,Gradle 只會產生包含所有 ABI 的程式碼和資源。universalApk 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