Custom fields for a build type in gradle

后端 未结 2 1274
别跟我提以往
别跟我提以往 2020-12-16 19:34

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

      

        
相关标签:
2条回答
  • 2020-12-16 20:30

    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.

    0 讨论(0)
  • 2020-12-16 20:40

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

    }

    0 讨论(0)
提交回复
热议问题