Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom fields for a build type in gradle

Tags:

android

gradle

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

like image 451
dlucci Avatar asked Jul 01 '14 20:07

dlucci


People also ask

What is a build type in Gradle?

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.

How do I get the current build type in Gradle?

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 { ... }


2 Answers

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.

like image 191
CommonsWare Avatar answered Oct 11 '22 22:10

CommonsWare


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";

}

like image 36
mbo Avatar answered Oct 11 '22 22:10

mbo