Gradle set property for specific buildType

1.5k Views Asked by At

How can I define a property and set it in a specific buildType?

I have already tried this:

android {
  project.ext.set("apis", "[]")

  buildTypes {
      release {
      ...
        project.apis = [
                    [
                            name   : "aaaa",
                            apiJson: "aaaa",
                            baseUrl: "aaaa"
                    ],
                    [
                            name   : "bbbb",
                            apiJson: "bbbb",
                            baseUrl: "bbbb"
                    ]
                 ]
      }

    debug{
      ...
        project.apis = [
                    [
                            name   : "cccc",
                            apiJson: "cccc",
                            baseUrl: "cccc"
                    ],
                    [
                            name   : "dddd",
                            apiJson: "dddd",
                            baseUrl: "dddd"
                    ]
                 ]
      }

   }

  func(apis)
}

From this, "api", always has the values of the last block. How can I dynamically set a property related to my current buildType until Gradle builds?

2

There are 2 best solutions below

0
On BEST ANSWER

i solved it in this way:

task config << {
    def apis
    switch (project.gradle.startParameter.taskNames[0]){
      case "app:assembleRelease":
          project.apis = [
                [
                        name   : "aaaa",
                        apiJson: "aaaa",
                        baseUrl: "aaaa"
                ],
                [
                        name   : "bbbb",
                        apiJson: "bbbb",
                        baseUrl: "bbbb"
                ]
             ]
         break;
      case "app:assembleDebug":
       apis = [
                [
                        name   : "cccc",
                        apiJson: "cccc",
                        baseUrl: "cccc"
                ],
                [
                        name   : "dddd",
                        apiJson: "dddd",
                        baseUrl: "dddd"
                ]
             ]
        ]
      break;
    }
    func(apis)
}
preBuild.dependsOn config
1
On

Try use buildConfigField. F.e.:

buildConfigField 'String', 'API_URL', '\"http://my.api.com\"'
buildConfigField 'boolean', 'LOG_ENABLED', 'true'

In your code:

String api = BuildConfig.API_URL;
if (BuildConfig.LOG_ENABLED){
...
}