无法使用 BuildConfig 访问 API 密钥

问题描述 投票:0回答:3

我正在使用 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
3个回答
1
投票
  1. 尝试将此行添加到

    app/build.gradle
    内的
    defaultConfig

    buildConfigField(“字符串”,“apiKey”,API_KEY)

  2. 然后尝试获取它

    String apiKey = BuildConfig.apiKey;


1
投票

我最终在应用程序的

local.properties
中读取了
build.gradle
中的 API 值并将其分配给
BuildConfig
。这是在
defaultConfig
标签下完成的。

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

0
投票

这个答案并不完全适用于我的 2023 年项目(Kotlin)。

local.properties

API_KEY=absdefghijklmnop

在我的应用程序级别

build.gradle.kts
我必须执行以下操作

buildFeatures.buildConfig = true // to enable custom build config keys

defaultConfig {
    ...
    ...
    val properties = Properties()
    properties.load(project.rootProject.file("local.properties").inputStream())
    buildConfigField("String", "API_KEY", properties.getProperty(("API_KEY")));
}

构建 > 清理项目

构建 > 重建项目

最后:

val apiKey = BuildConfig.API_KEY
Text(text = "API KEY ${apiKey}")
© www.soinside.com 2019 - 2024. All rights reserved.