ビルド バリアントを設定する

このページでは、以下のビルド バリアントを設定する方法について説明します。 1 つのプロジェクトから複数のバージョンのアプリを作成する方法、 依存関係と署名設定を適切に管理する必要があります。

各ビルド バリアントは、ビルド可能なさまざまなバージョンのアプリを表しています。たとえば、あるバージョンのアプリをビルドする 限定されたコンテンツによる無料のもの もう一つは より多い。API レベルまたは他のデバイスのバリエーションに基づいて、異なるデバイスをターゲットとするアプリの異なるバージョンをビルドすることもできます。

ビルド バリアントは、Gradle で特定の 構成、コード、リソースを集約するための一連のルールを ビルドタイプとプロダクト フレーバーを提供します。ビルド バリアントは構成しなくても ビルドタイプとプロダクト フレーバーを形成するプロダクト フレーバーを設定します。

例: 「デモ」プロダクト フレーバー: 特定の機能を指定する カスタム ソースコード、リソース、最小バージョンなどの制約を 「デバッグ」build type は、異なるビルドとコードを適用しています。 デバッグ オプションや署名鍵などのパッケージ化設定を管理します。「 この 2 つを組み合わせたビルド バリアントが「demoDebug」です。含まれている場合、 「デモ」に含まれる構成とリソースの組み合わせです。 プロダクト フレーバー、「debug」、ビルドタイプ、main/ ソースセットがあります。

ビルドタイプの設定

ビルドタイプは android 内で作成および設定できます。 ブロック内の build.gradle.kts ブロックを使用します。リージョン Android Studio が自動的にデバッグビルドとリリースビルドを作成し、 できます。デバッグ ビルドタイプはビルド構成に表示されませんが、 Android Studio は debuggable true を使用して設定します。これにより、安全な Android デバイス上でアプリをデバッグし、 汎用デバッグ キーストアを使用したアプリ署名を構成します。

特定の設定を追加または変更する場合、debug ビルドタイプを設定に追加することができます。次のサンプルでは、 デバッグ ビルドタイプ用の applicationIdSuffix と設定 「ステージング」debug ビルドタイプの設定を使用して初期化されるビルドタイプを指定します。

Kotlin

android {
    defaultConfig {
        manifestPlaceholders["hostName"] = "www.example.com"
        ...
    }
    buildTypes {
        getByName("release") {
            isMinifyEnabled = true
            proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
        }

        getByName("debug") {
            applicationIdSuffix = ".debug"
            isDebuggable = true
        }

        /**
         * The `initWith` property lets you copy configurations from other build types,
         * then configure only the settings you want to change. This one copies the debug build
         * type, and then changes the manifest placeholder and application ID.
         */
        create("staging") {
            initWith(getByName("debug"))
            manifestPlaceholders["hostName"] = "internal.example.com"
            applicationIdSuffix = ".debugStaging"
        }
    }
}

Groovy

android {
    defaultConfig {
        manifestPlaceholders = [hostName:"www.example.com"]
        ...
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            applicationIdSuffix ".debug"
            debuggable true
        }

        /**
         * The `initWith` property lets you copy configurations from other build types,
         * then configure only the settings you want to change. This one copies the debug build
         * type, and then changes the manifest placeholder and application ID.
         */
        staging {
            initWith debug
            manifestPlaceholders = [hostName:"internal.example.com"]
            applicationIdSuffix ".debugStaging"
        }
    }
}

注: ビルド構成ファイルに変更を加えると、Android Studio は新しい設定のプロジェクトを同期するよう要求します。プロジェクトを同期するには、[Sync Now] をクリックします。 メッセージを変更またはクリックしたときに表示される プロジェクトの同期アイコン を表示します。Android Studio が設定のエラーを通知する場合は、問題の説明が記載された [Messages] ウィンドウが表示されます。

ビルドタイプで構成できるすべてのプロパティについて詳しくは、 <ph type="x-smartling-placeholder"></ph>を読んで BuildType リファレンス。

プロダクト フレーバーの設定

プロダクト フレーバーの作成は、ビルドタイプの作成に似ています。プロダクト フレーバーを ビルド構成で productFlavors ブロックを指定し、必要な設定を含めます。 プロダクト フレーバーは、 defaultConfigdefaultConfig のため) 実際には <ph type="x-smartling-placeholder"></ph> ProductFlavor クラスを使用します。つまり、defaultConfig ブロックですべてのフレーバーの基本設定を提供でき、各フレーバーによって applicationId などのデフォルト値が変更される場合があります。宛先 アプリケーション ID について詳しくは、 アプリケーション ID を設定します

注: main/ マニフェスト ファイルの package 属性を使用してパッケージ名を指定する必要もあります。また、kubectl の「get」コマンドや ソースコード内のパッケージ名を使用して R クラスを参照したり、 。これにより、 applicationId: 各プロダクト フレーバーに一意の ID を パッケージ化して配布できます。

すべてのフレーバーは、名前の付いたフレーバー ディメンションに属していなければなりません。フレーバー ディメンションとは、プロダクト フレーバーのグループです。すべてのフレーバーをフレーバー ディメンションに割り当てる必要があります。 そうしないと、次のビルドエラーが発生します。

  Error: All flavors must now belong to a named flavor dimension.
  The flavor 'flavor_name' is not assigned to a flavor dimension.

特定のモジュールが フレーバー ディメンションを 1 つだけ指定すると、Android Gradle プラグインは自動的に モジュールのすべてのフレーバーをそのディメンションに割り当てます。

で確認できます。

次のサンプルコードでは、「version」という名前のフレーバー ディメンションを作成し、「demo」と「full」というプロダクト フレーバーを追加しています。これらのフレーバーには、独自の <ph type="x-smartling-placeholder"></ph> applicationIdSuffix および versionNameSuffix:

Kotlin

android {
    ...
    defaultConfig {...}
    buildTypes {
        getByName("debug"){...}
        getByName("release"){...}
    }
    // Specifies one flavor dimension.
    flavorDimensions += "version"
    productFlavors {
        create("demo") {
            // Assigns this product flavor to the "version" flavor dimension.
            // If you are using only one dimension, this property is optional,
            // and the plugin automatically assigns all the module's flavors to
            // that dimension.
            dimension = "version"
            applicationIdSuffix = ".demo"
            versionNameSuffix = "-demo"
        }
        create("full") {
            dimension = "version"
            applicationIdSuffix = ".full"
            versionNameSuffix = "-full"
        }
    }
}

Groovy

android {
    ...
    defaultConfig {...}
    buildTypes {
        debug{...}
        release{...}
    }
    // Specifies one flavor dimension.
    flavorDimensions "version"
    productFlavors {
        demo {
            // Assigns this product flavor to the "version" flavor dimension.
            // If you are using only one dimension, this property is optional,
            // and the plugin automatically assigns all the module's flavors to
            // that dimension.
            dimension "version"
            applicationIdSuffix ".demo"
            versionNameSuffix "-demo"
        }
        full {
            dimension "version"
            applicationIdSuffix ".full"
            versionNameSuffix "-full"
        }
    }
}

注: 以前に作成したレガシーアプリがある場合は、 2021 年 8 月)に Google Play で APK を使用して配信する場合、複数の APK を使用してアプリを配信できるようになります。 サポートしていない場合は、同じ applicationId 値を割り当てます。 各バリエーションに異なる値を割り当てる versionCode。配布方法 Google Play でアプリのさまざまなバリエーションを個別のアプリとして扱う場合は、 各バリエーションに異なる applicationId を割り当てる。

プロダクト フレーバーを作成して設定した後、通知バーで [Sync Now] をクリックします。同期が完了すると、Gradle は ビルドタイプとプロダクトに基づいてビルド バリアントを自動的に作成 さまざまなフレーバーがあり、 <product-flavor><Build-Type>。たとえば 「demo」を作成しましたと「full」プロダクト フレーバーがあり、デフォルトの "debug"および 「リリース」ビルドタイプに応じて、Gradle は次のビルド バリアントを作成します。

  • demoDebug
  • demoRelease
  • fullDebug
  • fullRelease

ビルドするビルド バリアントを選択し、 [Build] >[Select Build Variant] を選択して、 ビルド バリアントを選択します。ビルド バリアントの独自の機能や特徴のカスタマイズを開始するには、 使用する場合は、ソースの作成と管理を 使用できます

ビルド バリアント向けにアプリケーション ID を変更する

アプリの APK または AAB をビルドすると、ビルドツールによってアプリに build.gradle.ktsdefaultConfig ブロックで定義されたアプリケーション ID 必要があります。ただし、複数の異なるバージョンのテーブルを を Google Play ストアで個別の掲載情報(「無料」など)として表示する「pro」は 使用する場合は、個別のユーザー エージェントを ビルド バリアント。それぞれが異なる 指定します。

この場合、各ビルド バリアントを プロダクト フレーバーproductFlavors ブロック内のフレーバーごとに、applicationId プロパティを再定義するか、以下の例に示すように applicationIdSuffix を使用してデフォルトのアプリケーション ID の末尾にセグメントを付加することができます。

Kotlin

android {
    defaultConfig {
        applicationId = "com.example.myapp"
    }
    productFlavors {
        create("free") {
            applicationIdSuffix = ".free"
        }
        create("pro") {
            applicationIdSuffix = ".pro"
        }
    }
}

Groovy

android {
    defaultConfig {
        applicationId "com.example.myapp"
    }
    productFlavors {
        free {
            applicationIdSuffix ".free"
        }
        pro {
            applicationIdSuffix ".pro"
        }
    }
}

これにより、「free」プロダクト フレーバーのアプリケーション ID は「com.example.myapp.free」となります。

また、以下の例に示すように、applicationIdSuffix を使用し、ビルドタイプに基づいてセグメントを末尾に付加することもできます。

Kotlin

android {
    ...
    buildTypes {
        getByName("debug") {
            applicationIdSuffix = ".debug"
        }
    }
}

Groovy

android {
    ...
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
    }
}

Gradle はプロダクト フレーバーの後にビルドタイプ設定を適用するため、 「フリーデバッグ」のアプリケーション IDビルド バリアントが "com.example.myapp.free.debug"2 つのアプリで同じアプリケーション ID を使用することはできないため、この方法はデバッグビルドとリリースビルドの両方を同じデバイスに組み込みたい場合に便利です。

以前のアプリ(8 月より前に作成されたもの)がある場合 (2021 年)に、APK を使用して Google Play で配信され、同じアプリの掲載情報を使用して 複数の APK を配布し、 それぞれターゲットが異なるデバイス設定(API レベル、 各ビルド バリアントに同じアプリケーション ID を使用する必要がありますが、 別の versionCode を APK してください。詳しくは、複数 APK サポートをご覧ください。公開 1 つのアーティファクトを使用するため、AAB の使用は影響を受けません。 バージョン コードとアプリケーション ID がデフォルトで使用されます。

ヒント: マニフェスト ファイルでアプリケーション ID を参照する必要がある場合は、任意のマニフェスト属性で ${applicationId} プレースホルダを使用できます。Gradle はビルド時にこのタグを実際のアプリケーション ID に置き換えます。詳細については、ビルドの挿入 マニフェストに追加します

複数のプロダクト フレーバーとフレーバー ディメンションの組み合わせ

複数のプロダクト フレーバーの設定を組み合わせることが必要となる場合があります。たとえば、API レベルに応じて「full」と「demo」のプロダクト フレーバーで異なる設定を作成する必要がある場合などです。そのためには、 Android Gradle プラグインを使用すると、フレーバーとして複数のプロダクト フレーバーのグループを作成できます。 定義できます。

アプリをビルドする際、Gradle は定義された各フレーバー ディメンションに含まれるプロダクト フレーバー設定を組み合わせ、さらにビルドタイプ設定を使用して最終的なビルド バリアントを作成します。Gradle は 同じフレーバー ディメンションに属するプロダクト フレーバーを組み合わせる。

次のコードサンプルでは、 <ph type="x-smartling-placeholder"></ph> flavorDimensions プロパティを使用して「mode」を作成します。フレーバー グループ化して「フル」のおよび「demo」プロダクト フレーバーと「api」をフレーバー ディメンションを使用して、API レベルに基づいてプロダクト フレーバー構成をグループ化します。

Kotlin

android {
  ...
  buildTypes {
    getByName("debug") {...}
    getByName("release") {...}
  }

  // Specifies the flavor dimensions you want to use. The order in which you
  // list the dimensions determines their priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions += listOf("api", "mode")

  productFlavors {
    create("demo") {
      // Assigns this product flavor to the "mode" flavor dimension.
      dimension = "mode"
      ...
    }

    create("full") {
      dimension = "mode"
      ...
    }

    // Configurations in the "api" product flavors override those in "mode"
    // flavors and the defaultConfig block. Gradle determines the priority
    // between flavor dimensions based on the order in which they appear next
    // to the flavorDimensions property, with the first dimension having a higher
    // priority than the second, and so on.
    create("minApi24") {
      dimension = "api"
      minSdk = 24
      // To ensure the target device receives the version of the app with
      // the highest compatible API level, assign version codes in increasing
      // value with API level.
      versionCode = 30000 + (android.defaultConfig.versionCode ?: 0)
      versionNameSuffix = "-minApi24"
      ...
    }

    create("minApi23") {
      dimension = "api"
      minSdk = 23
      versionCode = 20000  + (android.defaultConfig.versionCode ?: 0)
      versionNameSuffix = "-minApi23"
      ...
    }

    create("minApi21") {
      dimension = "api"
      minSdk = 21
      versionCode = 10000  + (android.defaultConfig.versionCode ?: 0)
      versionNameSuffix = "-minApi21"
      ...
    }
  }
}
...

Groovy

android {
  ...
  buildTypes {
    debug {...}
    release {...}
  }

  // Specifies the flavor dimensions you want to use. The order in which you
  // list the dimensions determines their priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions "api", "mode"

  productFlavors {
    demo {
      // Assigns this product flavor to the "mode" flavor dimension.
      dimension "mode"
      ...
    }

    full {
      dimension "mode"
      ...
    }

    // Configurations in the "api" product flavors override those in "mode"
    // flavors and the defaultConfig block. Gradle determines the priority
    // between flavor dimensions based on the order in which they appear next
    // to the flavorDimensions property, with the first dimension having a higher
    // priority than the second, and so on.
    minApi24 {
      dimension "api"
      minSdkVersion 24
      // To ensure the target device receives the version of the app with
      // the highest compatible API level, assign version codes in increasing
      // value with API level.

      versionCode 30000 + android.defaultConfig.versionCode
      versionNameSuffix "-minApi24"
      ...
    }

    minApi23 {
      dimension "api"
      minSdkVersion 23
      versionCode 20000  + android.defaultConfig.versionCode
      versionNameSuffix "-minApi23"
      ...
    }

    minApi21 {
      dimension "api"
      minSdkVersion 21
      versionCode 10000  + android.defaultConfig.versionCode
      versionNameSuffix "-minApi21"
      ...
    }
  }
}
...

Gradle で作成されるビルド バリアントの数は、各フレーバー ディメンション内のフレーバーの数と、設定したビルドタイプをすべて乗算した数となります。Gradle が各ビルド バリアントまたは対応するアーティファクトに名前を付ける場合、 優先度の高いフレーバー ディメンションに属するフレーバーが最初に表示されます。 その次にビルドタイプが続きます。

使用 前のビルド構成と比較すると、Gradle は合計で 12 個の 次の命名スキームのビルド バリアントを作成します。

  • ビルド バリアント: [minApi24, minApi23, minApi21][Demo, Full][Debug, Release]
  • 対応する APK: app-[minApi24, minApi23, minApi21]-[demo, full]-[debug, release].apk
  • 次に例を示します。
    ビルド バリアント: minApi24DemoDebug
    対応する APK: app-minApi24-demo-debug.apk

個別のプロダクト フレーバーおよびビルド バリアント用のソースセット ディレクトリの作成に加え、プロダクト フレーバーの各組み合わせに対してもソースセット ディレクトリを作成することが可能です。たとえば Java ソースを src/demoMinApi24/java/ ディレクトリに追加します。 Gradle はこれらのソースを、次の要素を組み合わせてバリアントを作成する場合にのみ、 2 つのプロダクトフレーバーがあります

プロダクト フレーバーの組み合わせに対して作成したソースセットは、個別の各プロダクト フレーバーに属するソースセットより優先されます。ソースセットと Gradle でどのように リソースを統合する場合は、作成方法に関するセクションをお読みください。 ソースセットをご覧ください。

バリアントのフィルタリング

Gradle は、設定されたプロダクト フレーバーとビルドタイプのすべての可能な組み合わせでビルド バリアントを作成します。ただし、 不要なビルド バリアントや、 コンテキストを定義します。特定のビルド バリアント構成を削除するには、 モジュール レベルの build.gradle.kts でバリアント フィルタを作成する 表示されます。

例として前のセクションのビルド構成を使用し、アプリのデモバージョンでは API レベル 23 以上のみをサポートすると仮定します。variantFilter ブロックを使用して、「minApi21」と「demo」のプロダクト フレーバーを組み合わせたすべてのビルド バリアント設定を除外できます。

Kotlin

android {
  ...
  buildTypes {...}

  flavorDimensions += listOf("api", "mode")
  productFlavors {
    create("demo") {...}
    create("full") {...}
    create("minApi24") {...}
    create("minApi23") {...}
    create("minApi21") {...}
  }
}

androidComponents {
    beforeVariants { variantBuilder ->
        // To check for a certain build type, use variantBuilder.buildType == "<buildType>"
        if (variantBuilder.productFlavors.containsAll(listOf("api" to "minApi21", "mode" to "demo"))) {
            // Gradle ignores any variants that satisfy the conditions above.
            variantBuilder.enable = false
        }
    }
}
...

Groovy

android {
  ...
  buildTypes {...}

  flavorDimensions "api", "mode"
  productFlavors {
    demo {...}
    full {...}
    minApi24 {...}
    minApi23 {...}
    minApi21 {...}
  }

  variantFilter { variant ->
      def names = variant.flavors*.name
      // To check for a certain build type, use variant.buildType.name == "<buildType>"
      if (names.contains("minApi21") && names.contains("demo")) {
          // Gradle ignores any variants that satisfy the conditions above.
          setIgnore(true)
      }
  }
}
...

ビルド設定にバリアント フィルタを追加して、[Sync] をクリック 現在は、Gradle は次の条件を満たすビルド バリアントを無視します。 自動的に適用されます。ビルド バリアントがメニューに表示されなくなる [ビルド >メニューバーから [Build Variant] を選択します。 またはビルド バリアント ツール ウィンドウ バーをクリックします。

ソースセットの作成

Android Studio はデフォルトで、全ビルド バリアントで共有するすべての要素の main/ ソースセットとディレクトリを作成しますが、ただし、 新しいソースセットを作成して、Gradle がコンパイルするファイルと 特定のビルドタイプ、プロダクト フレーバー、さまざまな組み合わせに対応したパッケージを プロダクト フレーバー(フレーバーを使用する場合) ディメンションなど)、ビルド バリアントも参照できます。

たとえば、main/ ソースセットで基本的な機能を定義してプロダクト フレーバーのソースセットでクライアントごとにアプリのブランディングを変えることや、debug ビルドタイプを使用するビルド バリアント専用の特別なパーミッションやログ機能を含めることが可能です。

Gradle では、ソースセットのファイルとディレクトリが特定のフォルダで main/ ソースセットと同様に処理します。たとえば、Gradle の場合は 「デバッグ」に固有の Kotlin または Java クラスファイルを想定している使用するビルドタイプを src/debug/kotlin/ ディレクトリまたは src/debug/java/ ディレクトリ。

Android Gradle プラグインには、 ビルドタイプ、プロダクトごとに ファイルを整理できます ビルド バリアントに関するモジュールです。たとえば、以下のタスク出力サンプルは、Gradle で「debug」ビルドタイプの特定のファイルがあると予想される場所を示しています。

------------------------------------------------------------
Project :app
------------------------------------------------------------

...

debug
----
Compile configuration: debugCompile
build.gradle name: android.sourceSets.debug
Java sources: [app/src/debug/java]
Kotlin sources: [app/src/debug/kotlin, app/src/debug/java]
Manifest file: app/src/debug/AndroidManifest.xml
Android resources: [app/src/debug/res]
Assets: [app/src/debug/assets]
AIDL sources: [app/src/debug/aidl]
RenderScript sources: [app/src/debug/rs]
JNI sources: [app/src/debug/jni]
JNI libraries: [app/src/debug/jniLibs]
Java-style resources: [app/src/debug/resources]

この出力を表示する手順は次のとおりです。

  1. ツール ウィンドウ バーで [Gradle] をクリックします。
  2. [MyApplication] >ToDo リスト >android および sourceSets をダブルクリックします。

    [Tasks] フォルダを表示するには、Gradle で タスクリストを同期することもできます。方法は次のとおりです。

    1. [ファイル] >設定 >試験運用版Android Studio > [Settings] > [Experimental] など)。
    2. [Do not( Gradle 同期中に Gradle タスクリストを作成するをご覧ください。
  3. Gradle がタスクを実行すると、[Run] ウィンドウが開き、 出力です。

注: タスク出力には、アプリのテストを実行するために必要な test/androidTest/ といったテスト ソースセットなどのファイルのソースセットを管理する方法も示されています。

新しいビルド バリアントを作成する際に、Android Studio ではソースセット ディレクトリは作成されませんが、便利なオプションがいくつか提供されます。たとえば、「debug」ビルドタイプ用の java/ ディレクトリを作成するには次の手順で操作します。

  1. [Project] ペインを開き、 [Project] ビュー(ペイン上部のメニューから確認できます)
  2. MyProject/app/src/ に移動します。
  3. src ディレクトリを右クリックして、[ 新規 >ディレクトリ
  4. [Gradle Source Sets] の下のメニューから、[Gradle Source Sets] を選択します。 full/java
  5. Enter キーを押します。

Android Studio によってデバッグ ビルドタイプのソースセット ディレクトリが作成され、 次に、その中に java/ ディレクトリを作成します。または Android Studio は、新しいファイルをディレクトリに追加すると、 ビルド バリアントごとにビルドする必要があります。

たとえば、「debug」の値の XML ファイルを作成するには、ビルドタイプ:

  1. [Project] ペインで、src を右クリックします。 [新規] >XML > 値 XML ファイル
  2. XML ファイルの名前を入力するか、デフォルトの名前のままにします。
  3. [Target Source Set] の横にあるメニューから、[ debug)。
  4. [Finish] をクリックします。

「debug」ビルドタイプがターゲット ソースセットとして指定されているため、Android Studio は XML ファイルを作成するときに必要となるディレクトリを自動的に作成します。結果のディレクトリ構造は次のようになります。 図 1.

図 1. 「debug」の新しいソースセット ディレクトリビルド あります。

アクティブなソースセットのアイコンには、アクティブであることを示す緑色のインジケーターが表示されます。「 debug ソースセットには、マージされることを示す [main] が末尾に付加されています main ソースセットに追加します。

同じ手順で、src/demo/ などプロダクト フレーバーのソースセット ディレクトリや、src/demoDebug/ などビルド バリアントのソースセット ディレクトリを作成できます。また、src/androidTestDemoDebug/ など特定のビルド バリアントを対象とするテスト ソースセットも作成できます。詳細については、テスト ソースセットをご覧ください。

デフォルト ソースセットの設定を変更する

デフォルトのソースセット ファイルに整理されていないソースがある場合 構造を宣言する必要があります。 ソースセットの作成には、 <ph type="x-smartling-placeholder"></ph> sourceSets ブロックで、Gradle が収集する場所を変更する ソースセットの各コンポーネントのファイルを 記述することもできます

sourceSets ブロックは、 android ブロック内で指定します。別のクラウドプロバイダを ソースファイルGradle に指定する必要があるのは、 モジュール レベルの build.gradle.kts ファイル。Gradle は ソースセット コンポーネントごとにファイルを検索します。テストできるコンポーネントについては、 それらを複数のファイルやディレクトリにマッピングできるかどうか、 Android Gradle プラグイン API リファレンスをご覧ください。

次のコードサンプルは、app/other/ ディレクトリのソースをマッピングします。 main ソースセットの特定のコンポーネントに割り当てられ、 androidTest ソースセットのルート ディレクトリ:

Kotlin

android {
  ...
  // Encapsulates configurations for the main source set.
  sourceSets.getByName("main") {
    // Changes the directory for Java sources. The default directory is
    // 'src/main/java'.
    java.setSrcDirs(listOf("other/java"))

    // If you list multiple directories, Gradle uses all of them to collect
    // sources. Because Gradle gives these directories equal priority, if
    // you define the same resource in more than one directory, you receive an
    // error when merging resources. The default directory is 'src/main/res'.
    res.setSrcDirs(listOf("other/res1", "other/res2"))

    // Note: Avoid specifying a directory that is a parent to one
    // or more other directories you specify. For example, avoid the following:
    // res.srcDirs = ['other/res1', 'other/res1/layouts', 'other/res1/strings']
    // Specify either only the root 'other/res1' directory or only the
    // nested 'other/res1/layouts' and 'other/res1/strings' directories.

    // For each source set, you can specify only one Android manifest.
    // By default, Android Studio creates a manifest for your main source
    // set in the src/main/ directory.
    manifest.srcFile("other/AndroidManifest.xml")
    ...
  }

  // Create additional blocks to configure other source sets.
  sourceSets.getByName("androidTest") {
      // If all the files for a source set are located under a single root
      // directory, you can specify that directory using the setRoot property.
      // When gathering sources for the source set, Gradle looks only in locations
      // relative to the root directory you specify. For example, after applying the
      // configuration below for the androidTest source set, Gradle looks for Java
      // sources only in the src/tests/java/ directory.
      setRoot("src/tests")
      ...
  }
}
...

Groovy

android {
  ...
  sourceSets {
    // Encapsulates configurations for the main source set.
    main {
      // Changes the directory for Java sources. The default directory is
      // 'src/main/java'.
      java.srcDirs = ['other/java']

      // If you list multiple directories, Gradle uses all of them to collect
      // sources. Because Gradle gives these directories equal priority, if
      // you define the same resource in more than one directory, you receive an
      // error when merging resources. The default directory is 'src/main/res'.
      res.srcDirs = ['other/res1', 'other/res2']

      // Note: Avoid specifying a directory that is a parent to one
      // or more other directories you specify. For example, avoid the following:
      // res.srcDirs = ['other/res1', 'other/res1/layouts', 'other/res1/strings']
      // Specify either only the root 'other/res1' directory or only the
      // nested 'other/res1/layouts' and 'other/res1/strings' directories.

      // For each source set, you can specify only one Android manifest.
      // By default, Android Studio creates a manifest for your main source
      // set in the src/main/ directory.
      manifest.srcFile 'other/AndroidManifest.xml'
      ...
    }

    // Create additional blocks to configure other source sets.
    androidTest {

      // If all the files for a source set are located under a single root
      // directory, you can specify that directory using the setRoot property.
      // When gathering sources for the source set, Gradle looks only in locations
      // relative to the root directory you specify. For example, after applying the
      // configuration below for the androidTest source set, Gradle looks for Java
      // sources only in the src/tests/java/ directory.
      setRoot 'src/tests'
      ...
    }
  }
}
...

1 つのソース ディレクトリは 1 つのソースセットにのみ属すことができます。たとえば、 test ソースセットと androidTest ソースセットで同じテストソースを使用します。この これは、Android Studio でソースセットごとに個別の IntelliJ モジュールが作成されるため、 重複コンテンツ ルートが存在する場合があります。

ソースセットでビルドする

ソースセット ディレクトリには、特定の設定でのみパッケージ化するコードやリソースを入れておくことができます。たとえば 「demoDebug」をビルドするビルド バリアントは、モデルの 「demo」プロダクト フレーバーと「デバッグ」ビルドタイプに基づいて、Gradle は 次の優先順位を付けます。

  1. src/demoDebug/(ビルド バリアント ソースセット)
  2. src/debug/(ビルドタイプのソースセット)
  3. src/demo/(プロダクト フレーバーのソースセット)
  4. src/main/(メインのソースセット)

プロダクト フレーバーの組み合わせに対して作成されたソースセットには、すべてのフレーバー ディメンションを含める必要があります。 たとえば、ビルド バリアントのソースセットは、ビルドタイプとオール フレーバーの組み合わせにする必要があります。 定義できます。すべてではないものの複数をカバーするフォルダに関連するコードとリソースのマージ フレーバー ディメンションはサポートされていません。

複数のプロダクトを組み合わせた場合 プロダクト フレーバーのプロダクト フレーバーの優先度はフレーバーによって決まります。 グループ化しますラベルでフレーバーのディメンションをリストする場合、 <ph type="x-smartling-placeholder"></ph> android.flavorDimensions プロパティと、そのプロダクト フレーバーが リストにある最初のフレーバー ディメンションに属し、 というように 2 つ目のフレーバー ディメンションに属するものが抽出されます。また プロダクト フレーバーの組み合わせに対して作成したソースセットは、 各プロダクト フレーバーに属するソースセットよりも優先度が高くなります。

優先順位によって、どのソースセットが 優先されることもありません。demoDebug/ ソースセット ディレクトリにはそのビルド バリアント固有のファイルが含まれる可能性が高いため、debug/ で定義されているファイルが demoDebug/ に含まれている場合、Gradle は demoDebug/ ソースセットのファイルを使用します。Gradle では同様に、ビルドタイプとプロダクト フレーバーのソースセットのファイルに対して main/ にある同じファイルよりも高い優先度を付与します。Gradle では、以下のビルドルールを適用するときに、この優先順位が考慮されます。

  • kotlin/ ディレクトリまたは java/ ディレクトリ内のすべてのソースコードがコンパイルされる 単一の出力を生成します。

    注: 特定のビルド バリアントについて、Gradle はビルドをスローします。 2 つ以上のソース セット ディレクトリが定義されている場合に、 呼び出すことができます。たとえば、デバッグアプリをビルドする場合、 src/debug/Utility.ktsrc/main/Utility.kt。Gradle は両方を参照するため、 依存関係があり、「重複クラス」がスローされる エラーが発生します。別のバージョンの Utility.kt を 異なるビルドタイプを使用する場合は、各ビルドタイプで独自のバージョンの main/ ソースセットに含めないでください。

  • 複数のマニフェストは単一のマニフェストにマージされ、優先度が高い 順序は前の例のリストと同じです。つまり、ビルドタイプのマニフェスト設定により、プロダクト フレーバーなどのマニフェスト設定がオーバーライドされます。詳しくは、マニフェストのマージをご覧ください。
  • values/ ディレクトリ内のファイルが統合されます 説明します。2 つのファイルの名前が同じ場合(2 つのファイルなど) strings.xml ファイルの場合、優先度は 示しています。つまり、ビルドタイプのソースセットのファイルで定義されている値により、プロダクト フレーバーなどの同じファイルで定義されている値がオーバーライドされます。
  • res/asset/ ディレクトリのリソースは一緒にパッケージ化されます。同じ名前を持つリソースが Namespace に ソースセットが 2 つ以上ある場合、リストと同じ順序で優先度が与えられます。 説明しました。
  • Gradle がライブラリに含まれるリソースとマニフェストを提供する 依存関係がアプリをビルドするときに最も低い優先度になります。

依存関係の宣言

特定のビルド バリアントの依存関係を設定するには テスト ソースセット ビルド バリアントまたはテスト ソースセットの名前を Implementation キーワードを使用します。

Kotlin

dependencies {
    // Adds the local "mylibrary" module as a dependency to the "free" flavor.
    "freeImplementation"(project(":mylibrary"))

    // Adds a remote binary dependency only for local tests.
    testImplementation("junit:junit:4.12")

    // Adds a remote binary dependency only for the instrumented test APK.
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.5.1")
}

Groovy

dependencies {
    // Adds the local "mylibrary" module as a dependency to the "free" flavor.
    freeImplementation project(":mylibrary")

    // Adds a remote binary dependency only for local tests.
    testImplementation 'junit:junit:4.12'

    // Adds a remote binary dependency only for the instrumented test APK.
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.5.1'
}

依存関係の構成について詳しくは、このモジュールの ビルド依存関係を追加するをご覧ください。

バリアント認識型の依存関係管理を使用する

Android Gradle プラグイン 3.0.0 以降には、新しい依存関係メカニズムが組み込まれており、 は、ライブラリを使用するときにバリアントを照合します。アプリの debug バリアントを意味します は、ライブラリの debug バリアントを自動的に使用します。また、kubectl の フレーバー: アプリの freeDebug バリアントがライブラリの freeDebug を使用する あります。

プラグインでバリエーションを正確にマッチングさせるには、以下を行う必要があります。 一致する代替手段を用意する(説明のとおり) 直接一致が不可能な場合は次のセクションで説明します。

たとえば、アプリで「staging」というビルドタイプを設定しているにもかかわらず、 依存関係が維持されません。プラグインでアプリの「staging」バージョンをビルドしようとしたときに、どのバージョンのライブラリを使用すべきかを判断できません。そのため、次のようなエラー メッセージが表示されます。

Error:Failed to resolve: Could not resolve project :mylibrary.
Required by:
    project :app

バリアントのマッチングに関連するビルドエラーの解決

このプラグインには DSL 要素が含まれており、Gradle が以下の状況を解決する方法を制御できます。 アプリと依存関係の間で直接的なバリアント マッチングを行うことはできません。

バリアント認識型の依存関係マッチングに関連する問題と、 DSL プロパティを使用して解決します。

  • 依存関係にないビルドタイプがアプリに含まれている。

    たとえば、お客様のアプリには「ステージング」という言葉が含まれていますビルドタイプがありますが、依存関係にはビルドタイプのみ "debug"および「release」ビルドタイプ。

    なお、ライブラリの依存関係にビルドが含まれている場合でも、問題はありません。 おすすめしますこれは、プラグインが ビルドタイプをリクエストします。

    matchingFallbacks を使用して、特定のビルドタイプの代わりにマッチングするコードを指定します。 使用します。

    Kotlin

    // In the app's build.gradle.kts file.
    android {
        buildTypes {
            getByName("debug") {}
            getByName("release") {}
            create("staging") {
                // Specifies a sorted list of fallback build types that the
                // plugin can try to use when a dependency does not include a
                // "staging" build type. You may specify as many fallbacks as you
                // like, and the plugin selects the first build type that's
                // available in the dependency.
                matchingFallbacks += listOf("debug", "qa", "release")
            }
        }
    }

    Groovy

    // In the app's build.gradle file.
    android {
        buildTypes {
            debug {}
            release {}
            staging {
                // Specifies a sorted list of fallback build types that the
                // plugin can try to use when a dependency does not include a
                // "staging" build type. You may specify as many fallbacks as you
                // like, and the plugin selects the first build type that's
                // available in the dependency.
                matchingFallbacks = ['debug', 'qa', 'release']
            }
        }
    }
    
  • アプリとライブラリの両方に存在する特定のフレーバー ディメンション ライブラリに含まれていないフレーバーがアプリに含まれています。

    たとえば、アプリとそのライブラリ依存関係の両方に「tier」フレーバー ディメンションが存在するが、一方、「階層」では、アプリのディメンションに「無料」が含まれていると「有料」ありますが、 「demo」のみを含む依存関係と「有料」同じディメンションの複数のフレーバーがあります。

    アプリとそのライブラリの両方に存在する特定のフレーバー ディメンションの場合、 含まれている場合、アプリのプロダクト フレーバーがライブラリに含まれている場合でも、 できません。これは、プラグインが依存関係からそのフレーバーをリクエストすることはないためです。

    matchingFallbacks を使用して、アプリの「無料」に代わり一致するものを指定する プロダクト フレーバーを指定します。

    Kotlin

    // In the app's build.gradle.kts file.
    android {
        defaultConfig{
        // Don't configure matchingFallbacks in the defaultConfig block.
        // Instead, specify fallbacks for a given product flavor in the
        // productFlavors block, as shown below.
      }
        flavorDimensions += "tier"
        productFlavors {
            create("paid") {
                dimension = "tier"
                // Because the dependency already includes a "paid" flavor in its
                // "tier" dimension, you don't need to provide a list of fallbacks
                // for the "paid" flavor.
            }
            create("free") {
                dimension = "tier"
                // Specifies a sorted list of fallback flavors that the plugin
                // can try to use when a dependency's matching dimension does
                // not include a "free" flavor. Specify as many
                // fallbacks as you like; the plugin selects the first flavor
                // that's available in the dependency's "tier" dimension.
                matchingFallbacks += listOf("demo", "trial")
            }
        }
    }
    

    Groovy

    // In the app's build.gradle file.
    android {
        defaultConfig{
        // Don't configure matchingFallbacks in the defaultConfig block.
        // Instead, specify fallbacks for a given product flavor in the
        // productFlavors block, as shown below.
      }
        flavorDimensions 'tier'
        productFlavors {
            paid {
                dimension 'tier'
                // Because the dependency already includes a "paid" flavor in its
                // "tier" dimension, you don't need to provide a list of fallbacks
                // for the "paid" flavor.
            }
            free {
                dimension 'tier'
                // Specifies a sorted list of fallback flavors that the plugin
                // can try to use when a dependency's matching dimension does
                // not include a "free" flavor. Specify as many
                // fallbacks as you like; the plugin selects the first flavor
                // that's available in the dependency's "tier" dimension.
                matchingFallbacks = ['demo', 'trial']
            }
        }
    }
    
  • アプリに含まれていないフレーバー ディメンションがライブラリ依存関係に含まれている。

    たとえば、ライブラリ依存関係には「minApi」ディメンション用のフレーバーが含まれているが、アプリには「tier」ディメンション用のフレーバーしか含まれていない場合などです。"freeDebug" ビルドをビルドし、 使用していない場合、プラグインは「minApi23Debug」コードを使用するかどうかをまたは 「minApi18Debug」依存関係のバージョンを指定します。

    なお、ライブラリに含まれているフレーバー ディメンションがアプリに含まれている場合でも、問題はありません。 含まれません。プラグインでは、ライブラリ依存関係に存在するディメンションのみのフレーバーをマッチングするためです。たとえば、依存関係に ABI のディメンションが含まれていない場合、 「freeX86Debug」という「freeDebug」というコード ライブラリをバージョン 学びます。

    defaultConfig ブロックで missingDimensionStrategy を使用して、 プラグインのデフォルトのフレーバーで、存在しない各ディメンションから選択できます。下の図をご覧ください。 使用します。また、productFlavors ブロック内で選択肢をオーバーライドして、存在しないディメンションに対してフレーバーごとに異なるマッチング方針を指定することもできます。

    Kotlin

    // In the app's build.gradle.kts file.
    android {
        defaultConfig{
        // Specifies a sorted list of flavors that the plugin can try to use from
        // a given dimension. This tells the plugin to select the "minApi18" flavor
        // when encountering a dependency that includes a "minApi" dimension.
        // You can include additional flavor names to provide a
        // sorted list of fallbacks for the dimension.
        missingDimensionStrategy("minApi", "minApi18", "minApi23")
        // Specify a missingDimensionStrategy property for each
        // dimension that exists in a local dependency but not in your app.
        missingDimensionStrategy("abi", "x86", "arm64")
        }
        flavorDimensions += "tier"
        productFlavors {
            create("free") {
                dimension = "tier"
                // You can override the default selection at the product flavor
                // level by configuring another missingDimensionStrategy property
                // for the "minApi" dimension.
                missingDimensionStrategy("minApi", "minApi23", "minApi18")
            }
            create("paid") {}
        }
    }
    

    Groovy

    // In the app's build.gradle file.
    android {
        defaultConfig{
        // Specifies a sorted list of flavors that the plugin can try to use from
        // a given dimension. This tells the plugin to select the "minApi18" flavor
        // when encountering a dependency that includes a "minApi" dimension.
        // You can include additional flavor names to provide a
        // sorted list of fallbacks for the dimension.
        missingDimensionStrategy 'minApi', 'minApi18', 'minApi23'
        // Specify a missingDimensionStrategy property for each
        // dimension that exists in a local dependency but not in your app.
        missingDimensionStrategy 'abi', 'x86', 'arm64'
        }
        flavorDimensions 'tier'
        productFlavors {
            free {
                dimension 'tier'
                // You can override the default selection at the product flavor
                // level by configuring another missingDimensionStrategy property
                // for the 'minApi' dimension.
                missingDimensionStrategy 'minApi', 'minApi23', 'minApi18'
            }
            paid {}
        }
    }
    

詳細については、matchingFallbacks をご覧ください。 および missingDimensionStrategy Android Gradle プラグイン DSL リファレンスにあります。

署名設定の設定

Gradle は、明示的に定義しない限り、リリースビルドの APK または AAB に署名しません。 署名設定を指定します。署名鍵がない場合は、 アップロード鍵とキーストアを生成する 使用できます。

Gradle ビルド設定を使用して release ビルドタイプの署名設定を手動で設定するには、次の手順を行います。

  1. キーストアを作成します。キーストアはバイナリ ファイルであり、 秘密鍵が格納されています。キーストアは安全な場所に保管する必要があります。
  2. 秘密鍵を作成します。秘密鍵はアプリの署名に使用されます。 アプリに追加されたり、不正な第三者に開示されたりすることはありません。
  3. 署名設定をモジュール レベルの build.gradle.kts ファイルに追加します。

    Kotlin

    ...
    android {
        ...
        defaultConfig {...}
        signingConfigs {
            create("release") {
                storeFile = file("myreleasekey.keystore")
                storePassword = "password"
                keyAlias = "MyReleaseKey"
                keyPassword = "password"
            }
        }
        buildTypes {
            getByName("release") {
                ...
                signingConfig = signingConfigs.getByName("release")
            }
        }
    }

    Groovy

    ...
    android {
        ...
        defaultConfig {...}
        signingConfigs {
            release {
                storeFile file("myreleasekey.keystore")
                storePassword "password"
                keyAlias "MyReleaseKey"
                keyPassword "password"
            }
        }
        buildTypes {
            release {
                ...
                signingConfig signingConfigs.release
            }
        }
    }

注: リリースキーとキーストアのパスワードをビルドファイルに含めることは、セキュリティ上の理由からおすすめできません。代わりに、これらのパスワードを取得するようにビルドファイルを設定します。 環境変数から値を取得するか、ビルドプロセスで できます。

パスワードを環境変数から取得する方法:

Kotlin

storePassword = System.getenv("KSTOREPWD")
keyPassword = System.getenv("KEYPWD")

Groovy

storePassword System.getenv("KSTOREPWD")
keyPassword System.getenv("KEYPWD")

または、ローカルのプロパティ ファイルからキーストアを読み込むこともできます。セキュリティ上の理由から、 ソース管理に追加します。代わりに、サービスごとにローカルで 開発者です。詳しくは、<ph type="x-smartling-placeholder"></ph>をご覧ください ビルドファイルから署名情報を削除する

このプロセスが完了すれば、アプリを配布したり、Google Play で公開したりできます。

警告: キーストアと秘密鍵は安全な場所に保管し、セキュア バックアップを取るようにしてください。Play アプリ署名を使用していて、アップロード鍵を紛失した場合は、Play Console からリセットをリクエストできます。 Play アプリ署名を使用せずにアプリを公開する場合(2021 年 8 月より前に作成したアプリの場合)、アプリ署名鍵を紛失すると、それ以降アプリを更新できなくなります。アプリのすべてのバージョンに同じ署名鍵で署名する必要があるためです。

Wear OS アプリの署名

Wear OS アプリを公開する際は、スマートウォッチの APK とスマートフォンの APK(省略可)の両方を あります。Wear OS アプリのパッケージ化と署名について詳しくは、Wear アプリのパッケージ化と配布をご覧ください。