Android Exclude Api/Secret Key From Git

Oct 5, 2019

We wanted to prevent api/secret/private key from checking into git source control.

Solution 1: secret.properties

Create secret.properties in project directory.

GOOGLE_PLACES_API_KEY=AIzaXXXX

Add the following to .gitignore

# Secret
secret.properties

Add the following to module:app build.gradle

def secretFile = rootProject.file("secret.properties")
def secretProperties = new Properties()
secretProperties.load(new FileInputStream(secretFile))

android {

    defaultConfig {
        ...

        // buildConfigField("String", "GOOGLE_PLACES_API_KEY", secretProperties['GOOGLE_PLACES_API_KEY'])
        buildConfigField("String", "GOOGLE_PLACES_API_KEY", "\"${secretProperties['GOOGLE_PLACES_API_KEY']}\"")

        // optional - access via xml resource
        // resValue("string", "GOOGLE_PLACES_API_KEY", secretProperties['GOOGLE_PLACES_API_KEY'])
        resValue("string", "GOOGLE_PLACES_API_KEY", "${secretProperties['GOOGLE_PLACES_API_KEY']}")
    }
}

Access the api key in code

val key = BuildConfig.GOOGLE_PLACES_API_KEY

Access the api key in xml

@string/GOOGLE_PLACES_API_KEY

Solution 2: gradle.properties

NOT using gradle.properties in your project directory, but gradle.properties in C:\Users\[USERNAME]\.gradle. If the file doesn't exist, create it.

PROJECTX_GOOGLE_PLACES_API_KEY=AIzaXXXX

NOTE: Since all your project share the same global gradle.properties file, you might want to add project name as prefix to the key name.

Add the following to module:app build.gradle

android {

    defaultConfig {
        ...

        buildConfigField("String", "GOOGLE_PLACES_API_KEY", PROJECTX_GOOGLE_PLACES_API_KEY)
    }
}

Access the api key in code

val key = BuildConfig.GOOGLE_PLACES_API_KEY

Solution 3: via res/value/secret.xml

Add resource file res/values/secret.xml.

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

Add the following to .gitignore

# Secret
secret.xml

Access the api key in code

val key = context.getString(R.string.GOOGLE_PLACES_API_KEY)

Access the api key in xml

@string/GOOGLE_PLACES_API_KEY

Solution 4: Singleton Class

object AppKey {    const val GOOGLE_PLACES_API_KEY = "AIzaXXXX"}

Add the following to .gitignore

# Secret
AppKey.kt

Access the api key in code

val key = AppKey.GOOGLE_PLACES_API_KEY

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.