android - 如何改进在 Android 源代码中使用 HMS API key

标签 android api-key huawei-mobile-services

关于HMS API Key

使用HMS(华为移动服务)时,部分套件需要API key。 API key可以在AppGallery Connect -> [项目设置] -> [基本信息]中获取

AppGallery Connect

Android源码中HMS API key的重复定义

在源代码中,API key 通常如下使用。

[案例一]

主要 Activity .kt

// For example : private val API_KEY = "CgB6e3x9iW/qiE9l9wAUPK0e/bJQe5uIgTlYUD4bPc8gzjriSVxDDzX2fAVjCVdUHkP+tan0Xi0sf4tj7t11TJJe"
private val API_KEY = "Your API key"

// If using map kit
MapsInitializer.setApiKey(API_KEY)

[案例二]

字符串.xml

<!-- For example : <string name="api_key">CgB6e3x9iW/qiE9l9wAUPK0e/bJQe5uIgTlYUD4bPc8gzjriSVxDDzX2fAVjCVdUHkP+tan0Xi0sf4tj7t11TJJe</string> -->
<string name="api_key">Your API key</string>

主要 Activity .kt

// If using map kit
MapsInitializer.setApiKey(getString(R.string.api_key))

但是,这些情况必须直接将API key 放入源代码中。

实际上,在使用HSM时,您必须从AppGallery Connect下载agconnect-services.json并将其放在app文件夹下。

Android Studio Project

如果您打开 agconnect-services.json,您会发现 API key 已经包含在内。

agconnect-services.json

API key 会有重复的定义。不利于源代码中的 API key 管理。

解决方案

最好的解决方案是直接使用agconnect-services.json 中的API key ,不要在源代码中另行定义。下面是一个例子。

主要 Activity .kt

val api_key = AGConnectServicesConfig.fromContext(applicationContext).getString("client/api_key")

// If using map kit
MapsInitializer.setApiKey(api_key)

最佳答案

AGConnectServicesConfig 已弃用。你可以使用这个:

 val apiKey = AGConnectOptionsBuilder().build(this).getString("client/api_key")

从 agconnect-service.json 获取 key 。这可能对将来的某些人有帮助

关于android - 如何改进在 Android 源代码中使用 HMS API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63762926/

相关文章:

重新格式化xml布局代码后的android studio反向布局代码

android - CheckBox 如何获取其各自的可绘制对象?

java - 如何使用Java实现华为分块文件上传

android - 用户通过滑动删除华为设备后在前台重新启动通知(如 Strava/Endomondo)

java - 将数组列表从一个 Activity 发送到另一个 Activity 到 ListView android中

Android 使用 OKHTTP 单例进行 cookie 并行查询的正确方法

youtube-api - 如何在我的 Electron 应用程序中隐藏 API key ?

javascript - 我应该保守我的地理编码 api key 的 secret 吗?

r - 有没有办法混淆 R 包中的 API key ?

android - ZXing 与 Google Play 服务愿景