I was wondering what the best way of storing an api key is in android studio. I would want to exclude this file from github using gitignore.
I have seen some people use the gradle.properties in the HOME directory but the api is specific to my application.
I also notice there is a gradle.properties in a new android studio project but this can contain other things that I may not want to exclude.
Anyone know the best way to do this ?
So the file would be available locally and my project would read it at runtime but I would "maybe" gitignore this file so I wouldn't commit it so I would not expose my api key.
The only way to hide it is to proxy your request through your own server. Netlify Functions are a free way to add some simple backend code to a frontend app. This is this method I used while learning to program in college, where I needed to share my progress with my peer group without disclosing my API keys.
Instead of embedding your API keys in your applications, store them in environment variables or in files outside of your application's source tree.
I have seen some people use the gradle.properties in the HOME directory but the api is specific to my application.
I see no problem with API being specific to your app. We have similar situations sometimes, so we just use some unique name for gradle.properties
entries. Something like
(MY_APP_NAME)_(MY_API_NAME)_API_KEY
Also we're storing passwords to our internal Maven repositories in the same way, so they're not pushed to GitHub as part of build.gradle
file. I can say we're pretty happy with that approach.
Some alternatives which I can think about:
.gradle
file to your buildscript (which will contain your variables) using apply from: 'path-to-my-local-script.gradle'
. Just don't forget to add it to .gitignore
.You can store api keys with help of gradle and the system path variable Add new system PATH variable THE_MOVIE_DB_API_TOKEN="XXXXX":
Add the following code to the build.gradle file
apply plugin: 'com.android.application'
android {
...
defaultConfig {
...
}
buildTypes {
release {
...
}
buildTypes.each {
it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', "$System.env.THE_MOVIE_DB_API_TOKEN"
}
}
}
Use the API keys in Java code like this
BuildConfig.THE_MOVIE_DB_API_TOKEN)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With