I am trying to embed a few server addresses in my build.gradle file but I am unsure about how to do this. I know that in maven, you can write
<content.host>http://test.mysite.com</content.host>
and I can use content.host in my Android application. In gradle, I know you can create a build type by
buildTypes {
testBuild.initWith(buildTypes.debug)
testBuild{ /*test server info goes here*/ }
}
But I'm not sure how I can define content.host in gradle using that same method. Is there another way to define content.host in gradle or is there a way to add a custom property to buildTypes?
Cheers,
Derril
A build type determines how an app is packaged. By default, the Android plug-in for Gradle supports two different types of builds: debug and release . Both can be configured inside the buildTypes block inside of the module build file.
In your build. gradle (:app): tasks. all { Task task -> if (task.name == "preDebugBuild") { doFirst { //for debug build } } else if (task.name == "preReleaseBuild") { doFirst { //for release build } } } dependencies { ... }
Gradle for Android offers buildConfigField
, allowing you to add arbitrary data members to the code-generated BuildConfig
class:
buildTypes {
debug {
buildConfigField "String", "SERVER_URL", '"http://test.this-is-so-fake.com"'
}
release {
buildConfigField "String", "SERVER_URL", '"http://prod.this-is-so-fake.com"'
}
mezzanine.initWith(buildTypes.release)
mezzanine {
buildConfigField "String", "SERVER_URL", '"http://stage.this-is-so-fake.com"'
}
}
In your Java code, you can refer to BuildConfig.SERVER_URL
, and it will be populated with the string based on the build type you choose at compile time.
To just use a field independently from build types and product flavors, you could add it to your defaultConfig
by:
defaultConfig {
...
buildConfigField "String", "OS", '"android"'
}
Then the BuildConfig
looks like this:
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 = "1.0";
// Fields from default config.
public static final String OS = "android";
}
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