When you upload your Android app on GitHub, you need to hide it as no one has access to it except you. It is considered a security glitch, so that’s why it is important to hide your API key. I am going to show you how you can do that easily.
Some Developers store their API key in a String variable like this.
private static final String APK_KEY = "asjsdakf4d3ggs2ytm4x";
It is not good to push your secret things into a public repository as other people could use up your limited API calls. That’s probably the least concerning the situation. Sharing of API keys becomes more of a concern if the API key authenticates someone for access to a subset of data.
So, let’s see how we can do that.
local.properties
file:
apiKey="Your Key"
build.gradle
file:
def localProperties = new Properties()
localProperties.load(new FileInputStream(rootProject.file("local.properties")))
build.gradle
file:
android {
defaultConfig {
// ...
buildConfigField "String", "API_KEY",localProperties['apiKey']
}
}
4. Sync Gradle and build the project. You can now reference the key:
String apiKey = BuildConfig.API_KEY;
- Drive C
- Users folder
- your user folder
- .gradle folder
Create it here
- gradle.propertiesThen, write your APPNAME_API_KEY = "asjsdakf4d3ggs2ytm4x" inside it.
Save it as PROPERTIES File by enclosing with double quotes like this "gradle.properties"
Then, put your API key for debug and release purposes under buildTypes tree.
buildConfigField ‘String’, “ApiKey”, APPNAME_API_KEY
It will be like this:
buildTypes {
debug{
buildConfigField 'String', "ApiKey", APPNAME_API_KEY
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
buildConfigField 'String', "ApiKey", APPNAME_API_KEY
}
}
Sync it.
private static final String API_KEY = BuildConfig.ApiKey;
If ApiKey goes red, press the “Make Project” button or use Ctrl+F9
Sounds pretty easy, does it?. Whenever you upload your Android project on GitHub, the person that uses your repository will not be able to figure out what your API key is. Therefore, you are secure NOW.