Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve on using HMS API key in Android source code

About HMS API Key

When using HMS (Huawei Mobile Services), some kits need API key. API key can be get from AppGallery Connect -> [Project Setting] -> [General Information]

AppGallery Connect

Duplicate definitions of HMS API key in Android source code

Inside source code, API key is usually being used like following.

[Case 1]

MainActivity.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)

[Case 2]

strings.xml

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

MainActivity.kt

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

However, these cases have to put API key into source code directly.

Actually, when using HSM, you have to download agconnect-services.json from AppGallery Connect and put it under app folder.

Android Studio Project

If you open agconnect-services.json, you can find that API key is already included.

agconnect-services.json

There will be duplicate definitions of API key. It is not good for API key management in source code.

Solution

The best solution is to use the API key in agconnect-services.json directly and do not put another definition into source code. The following is an example.

MainActivity.kt

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

// If using map kit
MapsInitializer.setApiKey(api_key)
like image 381
Raymond Avatar asked Mar 08 '26 06:03

Raymond


1 Answers

AGConnectServicesConfig is deprecated. You can use this:

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

to get the key from agconnect-service.json. This might help some one in future

like image 122
waheed shah Avatar answered Mar 10 '26 16:03

waheed shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!