【 Android 中文開放式課程 】編譯配置環境參數 productFlavors & buildTypes


什麼是 productFlavors & buildTypes ,使用時機?
產品風味? coffee or tea?
我們常需要根據不一樣需求, 訂立區分不一樣的功能,最常見,範例:
- 「免費版」,提供簡單基本服務功能且 APP 畫面中會顯示廣告。
- 「付費版」,提供完整功能,不顯示廣告。
類似這樣的需求,我們就可以透過 productFlavors & buildTypes,編譯配置環境參數來切分出來。
另外,如果 APP 有串接後台伺服器,我們也一樣可以採用 productFlavors & buildTypes,來區分連結,如:開發區、正式區機器等設定。


如何設定 productFlavors ?
開啟專案中 build.gradle
android {
...
flavorDimensions "single"
productFlavors{
free{
buildConfigField "boolean", "IS_FREE", "true"
}
paid{
buildConfigField "boolean", "IS_FREE", "false"
}
}
buildTypes {
debug {
applicationIdSuffix ".debug"
resValue "string", "app_name", "[debug] HKT線上教室"
buildConfigField "String", "HOST", "\"http://tw-hkt.blogspot.tw/debug/\""
}
release {
applicationIdSuffix ".release"
resValue "string", "app_name", "[release] HKT線上教室"
buildConfigField "String", "HOST", "\"http://tw-hkt.blogspot.tw/\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
...
}
所以建置編譯 APP 時,就可以很方便透過選單,來切換所需要的執行環境:


實際在應用時,可以在自定義 Application 中,撈取 build.gradle 設定的環境參數:
public static final boolean IS_FREE = BuildConfig.IS_FREE;


HKT 線上教室 每週六日 更新影片
▶ YouTube 頻道
https://goo.gl/3f2pJi
▶ KT 線上教室 臉書粉絲團
https://goo.gl/27H9Li
▶ 贊助我們
https://goo.gl/FiKXAu
▶2017 Android 中文開放式課程 目錄
https://goo.gl/Ti8mGA
▶ YouTube 頻道
https://goo.gl/3f2pJi
▶ KT 線上教室 臉書粉絲團
https://goo.gl/27H9Li
▶ 贊助我們
https://goo.gl/FiKXAu
▶2017 Android 中文開放式課程 目錄
https://goo.gl/Ti8mGA
Android 8 Oreo / Android Studio
Android 教學 / 開發
Android 教學 / 開發