Safe Storage of an API Key in Android Studio

Lets imagine you’re building a nice app, one that connects to a third party service. Most APIs worth implementing feature an API key as a part of basic security. Checking this into source control isn’t the best idea. If you ever opensource your project (or parts of it) you can expose your key to any opportunistic github user.

One way to avoid this is to add the key to your file, then add this file to your git ignore (like anyone is using any other VCS system…I hear you shouting mecurial at me…If you’re shouting SVN….please stop). Magic, looks like this:

bighugelabs.key=“your key"

My build.gradle looks like this:

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
buildConfigField "String", "BIGHUGHE_LABS_KEY","bighugelabs.key")
        debug {
buildConfigField "String", "BIGHUGHE_LABS_KEY","bighugelabs.key")

Then in java I reference my key like this:

private static String API_KEY = BuildConfig.BIGHUGHE_LABS_KEY;

Now you can have a public repository that can reference API keys Or have different keys for debug and release! If there is a better way comment, mail or tweet me!