You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Secrets Gradle插件以编程方式获取Google Places API密钥?

问题描述

官方文档展示了如何在Manifest中通过Secrets Gradle插件使用存储在local.properties中的Google Maps密钥:

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}" />

但使用Places API时,需要以编程方式传入密钥:

Places.initialize(applicationContext, "API_KEY")

请问如何通过Secrets Gradle插件实现这一编程式调用的需求?

解决方案

按照以下步骤操作即可实现:

  1. 确认基础配置
    确保local.properties文件中已正确配置密钥:

    MAPS_API_KEY=你的谷歌地图API密钥
    

    同时项目已集成Secrets Gradle插件(未集成则完成基础插件配置流程)。

  2. 配置模块级build.gradle
    在应用模块(通常为app)的构建脚本中,添加配置让插件将密钥注入到BuildConfig类中:

    Groovy版本:

    android {
        // 其他配置项...
        buildFeatures {
            buildConfig true
        }
    }
    
    plugins {
        id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
    }
    
    secrets {
        propertiesFileName = "local.properties"
        generateBuildConfig = true
        buildConfigFields = [
            MAPS_API_KEY: "String"
        ]
    }
    

    KTS版本:

    android {
        // 其他配置项...
        buildFeatures {
            buildConfig = true
        }
    }
    
    plugins {
        id("com.google.android.libraries.mapsplatform.secrets-gradle-plugin")
    }
    
    secrets {
        propertiesFileName = "local.properties"
        generateBuildConfig = true
        buildConfigFields.put("MAPS_API_KEY", "String")
    }
    
  3. 在代码中调用密钥
    同步Gradle项目后,BuildConfig类会自动生成包含MAPS_API_KEY的字段,直接在代码中使用即可:

    Places.initialize(applicationContext, BuildConfig.MAPS_API_KEY)
    

内容的提问来源于stack exchange,提问作者user924

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:52:23