无法使用 BuildConfig 访问 API 键

Unable to access the API key using BuildConfig

我正在使用 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

然后,当我尝试从任何 class/application 访问它时,BuildConfig.apiKey 不存在。我在这里缺少任何步骤吗?已经尝试了几个小时,但没有找到任何方法来完成这项工作。

  1. 尝试在 defaultConfig

    中的 app/build.gradle 中添加这一行

    buildConfigField("字符串", "apiKey", API_KEY)

  2. 然后尝试获取它

    字符串 apiKey = BuildConfig.apiKey;

我最终在应用的 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')}\""