0

build.gradle中的我的 Android 项目中,使用以下说明创建构建配置字段

android {
    defaultConfig {
        if (project.hasProperty('serverOnePath')) {
            buildConfigField "String", "SERVER_ONE_PATH",
                    "\"${serverOnePath}\""
        }
        if (project.hasProperty('serverTwoPath')) {
            buildConfigField "String", "SERVER_TWO_PATH",
                    "\"${serverTwoPath}\""
        }
    }
}

因此,属性必须在gradle.properties中定义如下:

serverOnePath=http://example1.com/path
serverTwoPath=http://example2.com/path

我想将指令移到android.defaultlevel可用的函数中。这是一个非工作草案:

def addBuildConfigFieldIfPropertyIsPresent(
    String propertyName, String buildConfigFieldName) {
    if (project.hasProperty(propertyName)) {
        android.defaultConfig.buildConfigField "String", buildConfigFieldName,
                "\"${propertyName}\""
    }
}

棘手的部分是${propertyName}。将声明实际放入defaultConfig闭包中也会很好。

4

1 回答 1

4

尝试这个:

android {
  defaultConfig {
    def configFieldFromProp = { propName, constName ->
      if (project.hasProperty(propName)) {
        buildConfigField "String", constName, "\"${project[propName]}\""
      }
    }

    configFieldFromProp "serverOnePath", "SERVER_ONE_PATH"
    configFieldFromProp "serverTwoPath", "SERVER_TWO_PATH"
  }
}

您还可以将 guava 作为依赖项添加到您的构建脚本中,并使用它LOWER_CAMEL.to(UPPER_UNDERSCORE, propName)来避免两次键入相同的内容。

于 2015-02-09T11:02:29.707 回答