Manage environmental variables safely with Android Studio.

When you wanna share an Android app's source code on GitHub(or any sharing service), you shouldn't write any secret keys inside your app.
This is a way to hide these values from entire world. :)
 
1. Create or edit ~/.gradle/gradle.properties and define secret keys.
(Pay attention to the position, it's placed in USER HOME DIRECTORY!!!!!)

~/.gradle/gradle.properties

ProductionApiKey="production-api-key"
StagingApiKey="staging-api-key"


2. Read them in application level build.gradle.
In the example below, both of ProductionApiKey and StagingApiKey are named as "API_KEY".

app/build.gradle

flavorDimensions ( "api" )
productFlavors {
    prduction {
        dimension "api"
        buildConfigField "String", "API_KEY", ProductionApiKey
    }
    staging {
        dimension "api"
        buildConfigField "String", "API_KEY", StagingApiKey
    }
}


3. Use these values in your code.
Select productionDebug build variant and run it.
You'll see the log message "production-api-key". Yay!

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    System.out.println(BuildConfig.API_KEY); // -> production-api-key
}