Android 當Module多又要設定多Flavor該怎麼辦?

JLin
5 min readAug 12, 2024

--

每次在 Android 項目裡加新的 flavor,都得在每個模組的 build.gradle 文件裡配置一遍,真的很麻煩。這樣一來,工作量大增,還容易出錯。譬如我的submodule可能就有20個,這樣當我想要增加一個flavor或者在裡面增加一個 BuildConfigField,可能頭就開始暈了,這時候該怎麼辦呢?

增加SharedFlavors

這時候你應該希望可以只在一處寫flavor就可以在所有module通用對吧,但又不知道怎麼做,其實你可以在 project層的build.gradle

buildscript {
ext {
// here
}
}

譬如你的flavor可能這麼複雜

  productFlavors = {
standardPark {
dimension FLAVOR_DIMENSION
}

seasonalThemePark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_SEASONAL_THEME, TRUE
buildConfigField BOOLEAN, IS_IGNORE_CAPACITY_LIMITS, FALSE
}

miniPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_MINI_PARK, TRUE
}

betaPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_BETA_FEATURE, TRUE
}

nightPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_NIGHT_MODE, TRUE
}
}

於是乎在之前如果你要在每個地方都撰寫,或者之後增加屬性,有20個module就會需要改20次,非常的麻煩,於是乎其實你可以透過在上面所說觸增加一個sharedFlavors的定義

於是就會變成這樣

buildscript {
ext {
FLAVOR_DIMENSION = "parkExperience"

BOOLEAN = "boolean"
TRUE = "true"
FALSE = "false"

IS_SEASONAL_THEME = "IS_SEASONAL_THEME"
IS_MINI_PARK = "IS_MINI_PARK"
IS_VIRTUAL_QUEUE = "IS_VIRTUAL_QUEUE"
IS_NIGHT_MODE = "IS_NIGHT_MODE"

ENABLE_AR_ATTRACTIONS = "ENABLE_AR_ATTRACTIONS"
IS_WATER_PARK = "IS_WATER_PARK"
IS_FAST_PASS_ENABLED = "IS_FAST_PASS_ENABLED"
IS_FOOD_ORDERING_ENABLED = "IS_FOOD_ORDERING_ENABLED"
ENABLE_RIDE_PHOTOS = "ENABLE_RIDE_PHOTOS"
ENABLE_LIVE_SHOW_BOOKING = "ENABLE_LIVE_SHOW_BOOKING"
IS_BETA_FEATURE = "IS_BETA_FEATURE"
IS_ENABLE_VR_PREVIEW = "IS_ENABLE_VR_PREVIEW"
IS_IGNORE_CAPACITY_LIMITS = "IS_IGNORE_CAPACITY_LIMITS"

sharedFlavors = {
standardPark {
dimension FLAVOR_DIMENSION
}

seasonalThemePark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_SEASONAL_THEME, TRUE
buildConfigField BOOLEAN, IS_IGNORE_CAPACITY_LIMITS, FALSE
}

miniPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_MINI_PARK, TRUE
}

betaPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_BETA_FEATURE, TRUE
}

nightPark {
dimension FLAVOR_DIMENSION
buildConfigField BOOLEAN, IS_NIGHT_MODE, TRUE
}
}
}
}

然後在你各自的moduel中原本productFlavors處就會變成寫這樣就好了

android {
...
productFlavors sharedFlavors
....
}

就不需要一有異動,要在20處一起修改。

--

--

JLin

台中 / JAVA / Android /Kotlin / Kotlin Native 對於Kotlin衍生的JVM等技術 Compose for web / desktop / Ktor Server,生成式AI (Gemini/OpenAI)各式應用, 都有小興趣