Skip to content

Instantly share code, notes, and snippets.

@TheikChan
Forked from VDenis/store_api_keys.md
Created March 29, 2018 03:55
Show Gist options
  • Save TheikChan/66744e906f28591cd22ab1e0397b677f to your computer and use it in GitHub Desktop.
Save TheikChan/66744e906f28591cd22ab1e0397b677f to your computer and use it in GitHub Desktop.

1. Store api keys in a xml file

Put xml file "api_keys.xml" in the directory "res/value/".

api_keys.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="THE_MOVIE_DB_API_TOKEN">XXXXX</string>
</resources>

use api keys in java code

getString(R.string.THE_MOVIE_DB_API_TOKEN);

2.1 Store api keys with help of gradle and the gradle.properties file (Java)

Example_0 Example_1 Example_2

Add the following line to [USER_HOME]/.gradle/gradle.properties

For Windows OS, example for Denis user:

C:\Users\Denis\.gradle

gradle.properties

MyTheMovieDBApiToken="XXXXX"

Add the following code to the build.gradle file

build.gradle

apply plugin: 'com.android.application'

android {
    ...

    defaultConfig {
        ...
    }
    buildTypes {
        release {
            ...
        }
        buildTypes.each {
            it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', MyTheMovieDBApiToken
        }
    }
}

use api keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN)

2.2 Store api keys with help of gradle and the gradle.properties file (Java + XML)

gradle.properties

AppKey="XXXX-XXXX"

build.gradle

buildTypes {
//...
    buildTypes.each {
        it.buildConfigField 'String', 'APP_KEY_1', AppKey
        it.resValue 'string', 'APP_KEY_2', AppKey
    }
}

Usage in java code

Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));

BuildConfig.APP_KEY_1

Usage in xml code

<data android:scheme="@string/APP_KEY_2" />

3. Store api keys with help of gradle and the system path variable

Example_0

Add new system PATH variable THE_MOVIE_DB_API_TOKEN="XXXXX":

For Windows OS:

  • open system
  • advanced system settings
  • environment variables
  • add new variables to the user variables

Add the following code to the build.gradle file

build.gradle

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 api keys in java code

BuildConfig.THE_MOVIE_DB_API_TOKEN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment