在声明buildConfigField时使用local.properties字段

10
我有一个build.gradle和一个local.properties文件。我想在local.properties中声明一个值,在build.gradle中使用,该值未检入版本控制。
我已经通过buildConfigField使其工作:
buildTypes {
    debug {
        buildConfigField "String", "TEST", "test"
    }
}

很不幸,这会导致一个错误:
buildTypes {
    debug {
        buildConfigField "String", "TEST", local.properties.get("test")
    }
}

2
你可以在这里找到可供盗用的代码:https://dev59.com/r2Ij5IYBdhLWcg3wKiLs#20573171 - Scott Barta
1个回答

13

可以这样实现:

def getProps(String propName) {
  def propsFile = rootProject.file('local.properties')
  if (propsFile.exists()) {
    def props = new Properties()
    props.load(new FileInputStream(propsFile))
    return props[propName]
  } else {
    return "";
  }
}

在你的 buildTypes 块中:

buildTypes {
    debug {
        buildConfigField "String", "TEST", getProps("test")
    }
}

3
如果文件或属性名未找到,最好抛出异常,而不是默默返回null/空字符串。 - Vicky Chijwani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接