相信我,我已经查看了有关此主题的每个 SO 问题,但当我将地图键隐藏在 AndroidManifest.xml 之外时,无法显示 Google 地图。
我也查看了Docs,但我仍然陷入困境,因此发布此内容的原因。
mapskey.property 文件(也尝试过 local.properties 文件,但无济于事)
GOOGLE_MAPS_API_KEY = "ABCD1234" # not the actual key obviously
这个想法是将
mapskey.properties
文件放在 .gitignore
上,从而使其远离版本控制。
AndroidManifest.xml代码片段:
<uses-permission android:name="android.permission.INTERNET"/>
....
<meta-data android:name="com.google.android.geo.API_KEY"
android:value="${googleKey}"/>
build.gradle.kts文件代码片段:
android {
defaultConfig { ...
//load the values from .properties file
val mapsKeyFile = project.rootProject.file("mapskey.properties")
val properties = Properties()
properties.load(mapsKeyFile.inputStream())
//fetch the map key
val mapKey = properties.getProperty("GOOGLE_MAPS_API_KEY") ?: ""
//create a map of manifest placeholders
manifestPlaceholders["googleKey"] = mapKey
//define the resource value
resValue(type = "string", name = "googleKey", value = mapKey)
我尝试单独使用
manifestPlaceholder[]
,但地图没有显示。当我单独使用 resValue
时,出现此错误:
属性元数据#com.google.android.geo.API_KEY@value AndroidManifest.xml:32:13-40 需要占位符替换,但是 没有提供任何价值
显示地图的唯一方法是我将谷歌地图密钥直接插入清单或将其设置直接在manifestHolder上。
// Injecting the key directly on manifestPlaceholders is working
manifestPlaceholders["googleKey"] = "ABCD1234"
我在物理设备和 Android 模拟器上都尝试了代码,结果相同。我已经卸载/安装了该应用程序,但无济于事。我什至使用
buildConfigField()/ BuildConfig
常量进行了测试,该常量正在从 mapskey.properties 文件中正确读取和记录密钥。
毕竟我相信这不应该算作重复的问题,因为我需要真正的帮助来找出我的不足之处。
在为此苦苦挣扎了一段时间后,我意识到问题出在
mapskey.properties
属性文件上。这全归功于我所做的大量调试。
我已将密钥声明为:
// I wrapped the key within String quotes
GOOGLE_MAPS_API_KEY = "ABCD1234"
正确的方法是声明不带双引号的键。
// I wrapped the key within String quotes
GOOGLE_MAPS_API_KEY = ABCD1234
这是一场真正的斗争,我不能希望其他人如此。