As per google's recommendation putting restrictions such as specifying the package name and also the SHA-1 key is the way to go.
It has been explained here: https://cloud.google.com/docs/authentication/api-keys#securing_an_api_key
Now, the problem here is that whatever you do your API key will end up in the codebase i.e if you specify it outside your codebase (via some properties file) but pass it in via the BuildConfig field during the build phase (the whole key is visible to someone decompiling your code as it is now part of BuildConfig class file) or you split it up and concatenate in the codebase (the split keys are still visible and anyone can concatenate them by seeing the usage to get the final key from a decompiled apk).
The split key version will get rid of the warning in the Play Console, but the key is still exposed.
My suggested solution thus would be to encode your API key and pass that around your codebase. Just before using it you decode it back.
A very simple example can be:
Please use a better encoding algo and not this, this is for demonstration purpose only. Here we are using Base64 encoding.
import android.util.Base64
fun main() {
// API Key = "123456ABC"
val myEncodedApiKey = "MTIzNDU2QUJD" // Should be passed via BuildConfig
val decodedApiKey = Base64.decode(myEncodedApiKey, Base64.DEFAULT)
// Now use `decodedApiKey` in your codebase.
val decodedApiKeyString = String(decodedApiKey)
}
Why is this better?
- Your key is not exactly the same as in your GCP project.
- The play console when it scans your codebase, cannot match it back to your GCP project API keys. Thus no warnings.
Update (clarification on using the google-services.json file for API key):
The solution to use the API key from google-services.json isn't quite valid. google-services.json is generated file usually if you connect your firebase account. The API key defined there has a different restriction model. The one you define in your GCP project is different, allowing you to pass in package name and an SHA-1 key as well as restricted to a specific kind of API access such as Youtube only access. So if one was to use the API keys from google-services.json then you are essentially not using the restrictions you set up in your GCP account. GCP accounts do not generate google-services.json file.
To bring into perspective here is an official doc from Google for setting up Youtube API which uses GCP project defined API keys and in the docs, it mentions to directly put the keys in the code. (which is anyways wrong as it is exposed, but that's Google for you).
https://developers.google.com/youtube/android/player/setup
Nowhere in any docs, it is referred to use google-services.json file for retrieving API keys.