I have situation where I have multiple flavors of my app. For ex. Dev, Stage, Production flavors.
So, dev will be pointing to dev server url, dev app id etc. and same for stage and production. For app id which are present in my strings.xml, I can replace them using following code -
variant.mergeResources.doLast {
File valuesFile = file("${buildDir}/res/all/${variant.dirName}/values/values.xml")
println("Replacing app id in " + variant.dirName)
String content = valuesFile.getText('UTF-8')
def appid;
String variantDirName = variant.dirName;
if (variantDirName.contains("dev")) {
appid = '1234_dev'
} else if(variantDirName.contains("stage")) {
appid = '1234_stage'
} else if(variantDirName.contains("prod")) {
appid = '1234_prod'
} else {
appid = '1234_unknown'
}
content = content.replaceAll(/some_app_id/, appid)
valuesFile.write(content, 'UTF-8')
}
where my strings.xml is -
<string name="app_id">some_app_id</string>
Now, server urls are stored in my Config.java file as normal constant-
public static final String BASE_URL = "http://dev.blahblah.com";
So the question is how to change this line in Config.java from my build.gradle file depending upon different flavor?
You can use BuildConfig as Xavier sad. Example:
In product flavors
productFlavors {
develop {
applicationId "com.dexode.cree.develop"
ext.enableCrashlytics = false
buildConfigField "String", "API_URL", "\"https://api.test.dexode.com/2.3\""
}
beta {
applicationId "com.dexode.cree.beta"
ext.enableCrashlytics = true
buildConfigField "String", "API_URL", "\"https://api.dexode.com/2.3\""
}
production {
ext.enableCrashlytics = true
buildConfigField "String", "API_URL", "\"https://api.dexode.com/2.3\""
}
So now your BuildConfig looks like:
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.dexode.cree.develop.debug";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "develop";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0.0.0_debug";
// Fields from product flavor: develop
public static final String API_URL = "https://api.test.dexode.com/2.3";
}
And usage in code:
RestAdapter.Builder builder = new RestAdapter.Builder().setEndpoint(BuildConfig.API_URL);
Remember to refresh content of file BuildConfig. AndroidStudio like to cache files. You can click File -> Synchronize
Documentation about Flavors
Related question buildConfigField depending on flavor + buildType
You shouldn't edit the output of existing tasks like this, this is going to break incremental support and every time you build, it'll rerun the mergeResource task (because its output were changed).
In this case I'd simply use resConfig
and buildConfigField
to dynamically create a res and a constant field in BuildConfig
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With