はじめに
Android開発でProductFlavorはよく使いますが、
はじめに一回きりか予め別の人が設定しているかで自分が理解する機会をえれていなかったので、
覚書を残します。
環境
AndroidStudio 3.5.1
業務でよく使うパターン、覚えておきたいこと
例題(要件)
- 開発環境、ステージング環境が2つ(stg1 / stg2)、本番環境がある
- それぞれ別のアプリでインストール・起動・テストをしたい
- 一部の処理を各環境ごとに変更したい
初期状態のbuild.gradle(app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "sample.my.mvvm_bmi"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
// 省略
}
要件ごとの実装例
開発環境、ステージング環境が2つ(stg1 / stg2)、本番環境がある
AndroidStudioであれば、[File] -> Procjet Structureから
GUIでFlavorを設定できます。
AddDimensionでFlavorDimensionsを設定して、その後ProductFlavorを設定します。
設定後
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "sample.my.mvvm_bmi"
minSdkVersion 28
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
flavorDimensions 'environment'
productFlavors {
dev {
dimension = 'environment'
}
stg1 {
dimension = 'environment'
}
stg2 {
dimension = 'environment'
}
prd {
dimension = 'environment'
}
}
}
dependencies {
// 省略
}
それぞれ別のアプリでインストール・起動・テストをしたい
ProductFlavorの登録画面で Application Id Suffix と
Version Name Suffix を設定すればOKです。
一部の処理を各環境ごとに変更したい
https://developer.android.com/studio/build/build-variants?hl=ja#sourcesets
を参考に、各Flavorごとのjavaフォルダ、resフォルダを作成します。
AndroidStudioでproductFlavorと同名のフォルダを紐づけてくれるので、
かなり直感的です。
おまけ
https://developer.android.com/studio/build/build-variants?hl=ja#filter-variants
にある通り、特定のビルドバリアントを設定しないようにもできます。
キャプチャはproductionはdebugビルドなしの設定をしています。
まとめ
逆引きっぽくなってしまいましたが、自分が今まで見てきたパターンをまとめてみました。
Androidの公式サイトにも綺麗に書かれています。
また、こちらのページも綺麗にまとめられていて、非常に参考になりました。