Android build types and build variants
During development, we might need to configure the code to use different api endpoint, or other environment variables for dev, staging and prod builds. This can be done by defining different build types in the Android app build gradle file.
Here is the an example configuration for defining different build types, debug, dev, staging and release.
android { signingConfigs { config { keyAlias 'build_variant' keyPassword 'android' // update this path to your keystore file path storeFile file('/path/to/the/android/project/folder/app/debug.keystore') storePassword 'android' } } buildTypes { debug { applicationIdSuffix = ".debug" versionNameSuffix "-debug" } dev { initWith debug applicationIdSuffix = ".dev" versionNameSuffix "-dev" debuggable true } staging { initWith debug applicationIdSuffix = ".staging" versionNameSuffix "-staging" } release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.config } } }
Let’s create a strings.xml in each of the following path with different values assigned to the string variable build_type and api_domain.
app/src/debug/res/values/strings.xml
Build Variants Debug https://debug.example.com
app/src/dev/res/values/strings.xml
Build Variants Dev https://dev.example.com
app/src/staging/res/values/strings.xml
Build Variants Staging https://staging.example.com
app/src/release/res/values/strings.xml
Build Variants Release https://www.example.com
app/src/main/res/values/strings.xml
Build Variants Build Type
In the code, it is the same as to how to pulling in the string resources, here is the example of setting a TextView with a string from the strings.xml, it will get the appropriate strings.xml according to the selected build variant.
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // for a staging build, it will get the api_domain defined in the in the staging folder. and for other builds, it will get the api_domain defined in other folder. tv_domain.text = getString(R.string.api_domain) } }
The build variant can be select by Click the build variant on the left bottom, and select the build variant. For example, if the staging build variant is selected, the apk will use the strings.xml from app/src/staging/res/values/strings.xml. This applies to other resources as well, such as drawables, colors, integers, etc.
Search within Codexpedia
Search the entire web