【问题标题】:Unable to access the API key using BuildConfig无法使用 BuildConfig 访问 API 密钥
【发布时间】:2022-02-03 11:28:36
【问题描述】:

我正在使用 secrets-gradle-plugin 读取我放入 local.properties 中的 API 密钥。

我已将此代码添加到根build.gradle

buildscript {
  dependencies {
    classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.0"
  }
}

对于应用程序build.gradle

plugins {
  id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}

android {
  compileSdk 31
...
}

这是我的local.properties

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#
sdk.dir=/Users/xxx/Library/Android/sdk
apiKey=YOUR_API_KEY

然后,当我尝试从任何类/应用程序访问它时,BuildConfig.apiKey 不存在。我在这里错过任何步骤吗?尝试了几个小时,但没有找到任何方法来完成这项工作。

【问题讨论】:

标签: android gradle google-api api-key secret-key


【解决方案1】:
  1. 尝试将此行添加到app/build.gradle 中的defaultConfig

    buildConfigField("String", "apiKey", API_KEY)

  2. 然后尝试获取它

    String apiKey = BuildConfig.apiKey;

【讨论】:

  • 我可以通过使用此代码buildConfigField "String", "API_KEY", "\" API_KEY\"" 获取值但是使用这意味着我需要将密钥放入应用程序build.gradle 中,它将被推送到 git 中。这是我使用这个秘密 gradle 插件的主要原因。我可以使用这种方式但从local.properties 获取数据吗?
  • 好的,找到了。我用它从local.properties 加载数据。 Properties properties = new Properties()properties.load(project.rootProject.file('local.properties').newDataInputStream())buildConfigField "String", "API_KEY", ${properties.getProperty('API_KEY')}
  • 是的,将 apikeys 放在属性文件中通常不是一个好习惯。但如果它只是一个测试项目,那么我想它很好。
【解决方案2】:

我最终在应用程序的build.gradle 中读取local.properties 中的API 值并将其分配给BuildConfig。这是在defaultConfig 标签下完成的。

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream()) 
buildConfigField "String", "API_KEY", "\"${properties.getProperty('API_KEY')}\""

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2019-04-21
    相关资源
    最近更新 更多