如果 Android Gradle Build 中不存在默认属性文件,如何创建它

Jon*_*Jon 4 groovy android gradle android-gradle-plugin

目前,我的 android 项目从本地属性文件加载两个参数来填充一些Build.Config常量。拥有单独文件的目的local.properties是使其不受源代码控制。(该文件被 git 忽略)。其中的值对于生产版本没有任何价值,并且可能会被开发人员频繁更改。我不希望这些值的更改构成build.gradle. 我也不希望它仅仅因为开发人员检查了不同的 git 分支而改变。

我的问题是,由于此属性文件不在源代码管理中,因此新的克隆和签出将无法构建,因为该文件不存在。在该文件不存在的情况下,我希望脚本创建它并将默认参数保存到其中。

ERROR: C:\Users\Me\AndroidStudioProjects\MyAwesomeApp\app\local.properties (系统找不到指定的文件)

我当前build.gradle从属性文件中读取:

Properties properties = new Properties()
properties.load(project.file('local.properties').newDataInputStream())
def spoofVin = properties.getProperty('spoof.vin', '12345678901234567')
def spoofId = properties.getProperty('spoof.id', '999999999999')
buildConfigField("String", "SPOOF_VIN", '"' + spoofVin + '"')
buildConfigField("String", "SPOOF_ID", '"' + spoofId + '"')
Run Code Online (Sandbox Code Playgroud)

示例app/local.properties文件:

#Change these variables to spoof different IDs and VINs. Don't commit this file to source control.
#Wed Nov 18 12:13:30 CST 2020
spoof.id=999999999999
spoof.vin=12345678901234567
Run Code Online (Sandbox Code Playgroud)

我在下面发布我自己的解决方案,希望可以帮助其他有相同需求的人。我不是 Gradle 专业人士,所以如果您知道更好的方法来做到这一点,请发布您的解决方案。

Jon*_*Jon 5

以下代码是我发现可以完成此任务的代码。该properties.store方法还可以方便地让我将字符串注释添加到properties.local 文件的顶部。

//The following are defaults for new clones of the project.
//To change the spoof parameters, edit local.properties
def defaultSpoofVin = '12345678901234567'
def defaultSpoofId = '999999999999'
def spoofVinKey = 'spoof.vin'
def spoofIdKey = 'spoof.id'

Properties properties = new Properties()
File propertiesFile = project.file('local.properties')
if (!propertiesFile.exists()) {
    //Create a default properties file
    properties.setProperty(spoofVinKey, defaultSpoofVin)
    properties.setProperty(spoofIdKey, defaultSpoofId)

    Writer writer = new FileWriter(propertiesFile, false)
    properties.store(writer, "Change these variables to spoof different IDs and VINs. Don't commit this file to source control.")
    writer.close()
}

properties.load(propertiesFile.newDataInputStream())
def spoofVin = properties.getProperty(spoofVinKey, defaultSpoofVin)
def spoofId = properties.getProperty(spoofIdKey, defaultSpoofId)
buildConfigField("String", "SPOOF_VIN", '"' + spoofVin + '"')
buildConfigField("String", "SPOOF_ID", '"' + spoofId + '"')
Run Code Online (Sandbox Code Playgroud)

  • @KhushbuShah,多年后这对我来说仍然是最好的解决方案。我喜欢它,因为它创建属性文件,开发人员将有一个现有的模板文件需要修改,而不需要从头开始使用密钥创建文件。 (2认同)