3

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)
Raymond
  • 61
  • 1

2 Answers2

2

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

tanutapi
  • 1,083
  • 9
  • 7
waheed shah
  • 494
  • 7
  • 19
1

I used map kit recently. I use the map kit version:

implementation 'com.huawei.hms:maps:5.1.0.300'

It's more simple now. If agconnect-services.json and *.jks is included and well configured as the huawei official site: https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/android-sdk-config-agc-0000001061560289-V5

The MapsInitializer.setApiKey(api_key) have not be needed to write.

//        MapsInitializer.setApiKey("Your API key");

The official SDK demo may contains MapsInitializer.setApiKey("Your API key") in its java code; Could unline it if agconnect-services.json has be configured.

Matrix
  • 503
  • 3
  • 17