【问题标题】:Gradle build won't find the apikey.properties file in root folderGradle 构建在根文件夹中找不到 apikey.properties 文件
【发布时间】:2024-04-16 14:15:02
【问题描述】:

我正在尝试添加一个带有一些客户端 ID 和机密的 apikey.properties 文件以获取令牌。

尝试 Victory 在此线程中给出的示例后遇到的问题: Where to keep the OAuth client credentials on Android

我在尝试构建时遇到了这个问题:

Build file 'C:\app root\app\build.gradle' line: 7

A problem occurred evaluating project ':app'.
> C:\app root\apikey.properties (The system cannot find the file specified)

build.gradle(:app):

...
def apikeyPropertiesFile = rootProject.file("apikey.properties")
def apikeyProperties = new Properties()
apikeyProperties.load(new FileInputStream(apikeyPropertiesFile))
...

...
 // should correspond to key/value pairs inside the file
        buildConfigField("String", "scope", apikeyProperties['scope'])
        buildConfigField("String", "client_id", apikeyProperties['client_id'])
        buildConfigField("String", "client_secret", apikeyProperties['client_secret'])
        buildConfigField("String", "grant_type", apikeyProperties['grant_type'])
...

apikey.properties 文件:

scope=xxx
client_id=xxx
client_secret=xxx
grant_type=xxx

不确定我在这里做错了什么,感谢任何帮助!

【问题讨论】:

  • 您是否按照示例中的说明将文件放入`project/apikey.properties` 中?相对于project/app/build.gradle 文件。
  • 是的,这些值在 Intellij 中突出显示,当将 apikey.propeties 移动到其他位置时,它们不再被发现。所以看起来变量会以某种方式传播,但是在构建时没有找到文件......下面的 BroscR 发布了一个可行的解决方案..

标签: android build.gradle properties-file


【解决方案1】:

试试这个。

gradle 文件..

    Properties properties = new Properties()
    if (rootProject.file("apikey.properties").exists()) {
        properties.load(rootProject.file("apikey.properties").newDataInputStream())
    }
    def mapsApiKey = properties.getProperty("MAPS_API_KEY")
     defaultConfig {
 buildConfigField("String", "MAPS_API_KEY", "\"$mapsApiKey\"")
}

apikey.properties..

MAPS_API_KEY=AIzqwdqwdqwdqwdqwdqdww

【讨论】:

  • 谢谢!工作正常。你知道我是否可以在 Azure DevOps 中使用 Replace Tokens 来替换这些值吗? marketplace.visualstudio.com/items?itemName=qetza.replacetokens
  • 不,我不知道。很抱歉,如果您愿意,可以创建新问题..
  • 好的,是的,会尝试一下,看看它是否有效,否则会发布一个新问题。再次感谢!