How to get the build variant at runtime in Android Studio?
Another option would be to create a separate build config variable for each build variant and use it in your code like this:
In your build.gradle file:
productFlavors {
production {
buildConfigField "String", "BUILD_VARIANT", "\"prod\""
}
dev {
buildConfigField "String", "BUILD_VARIANT", "\"dev\""
}
}
To use it in your code:
if (BuildConfig.BUILD_VARIANT.equals("prod")){ // do something cool }
Here is an example to define and get BuildConfig
for different flavor
android {
defaultConfig {
...
buildTypes {
...
}
flavorDimensions "default"
productFlavors {
develop {
applicationIdSuffix ".dev"
versionNameSuffix "-dev"
}
staging {
applicationIdSuffix ".stg"
versionNameSuffix "-stg"
}
production {
applicationIdSuffix ""
versionNameSuffix ""
}
}
applicationVariants.all { variant ->
def BASE_URL = ""
if (variant.getName().contains("develop")) {
BASE_URL = "https://localhost:8080.com/"
} else if (variant.getName().contains("staging")) {
BASE_URL = "https://stagingdomain.com/"
} else if (variant.getName().contains("production")) {
BASE_URL = "https://productdomain.com/"
}
variant.buildConfigField "String", "BASE_URL", "\"${BASE_URL}\""
}
}
Using
BuildConfig.BASE_URL
Look at the generated BuildConfig
class.
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.app";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "";
}