在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.default
level可用的函数中。这是一个非工作草案:
def addBuildConfigFieldIfPropertyIsPresent(
String propertyName, String buildConfigFieldName) {
if (project.hasProperty(propertyName)) {
android.defaultConfig.buildConfigField "String", buildConfigFieldName,
"\"${propertyName}\""
}
}
棘手的部分是${propertyName}
。将声明实际放入defaultConfig
闭包中也会很好。