Cody Blog

Software development

How to storing api keys in Android

You SHALL not save api key into version control system, but how can you manage your API keys?

There are some approaches had been discussed here. One is to saving the api key in gradle.properties. Before add secret to this file. you need add gradle.properties to .gitignore file. If you already commited this file to your git. remove gradle.properties from git first by this command:

git rm --cache gradle.properties

Next, Open your gradle.properties and appmend a new line:

yourapikey="THIS IS API TOKEN"

Modify build.gradle and add buildConfigField for your api key

android {
    compileSdkVersion 24
    ...
    buildTypes {
        ...

        buildTypes.each {
            it.buildConfigField 'String', 'YOU_API_KEY', yourapikey
        }
    }
}

After gradle sync finished. BuildConfigVariable is auto generated to

public final class BuildConfig {
...
public static final String YOU_API_KEY = "12345";
}

Using BuildConfig.OPENWEATHER_API_KEY to reference the api key.

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("www.helloworld.com");
urlBuilder.appendQueryParameter("key", BuildConfig.YOU_API_KEY);

That's it!

Android

Related Posts

Comments