Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ed828a/a80800032eff40eb12b6fa8144068b3a to your computer and use it in GitHub Desktop.
Save ed828a/a80800032eff40eb12b6fa8144068b3a to your computer and use it in GitHub Desktop.

Hiding API keys in local.properties

  1. Make sure your build directory is gitignored. It should be, by default, in a new Android Studio project -- you can double check by making sure that your .gitignore file contains the line:
/build
  1. In your project root directory, add the API key to local.properties file like this:
apiKey="hgjfkhg5764317698315768549027nfdsngadf"

Where hgjfkhg5764317698315768549027nfdsngadf would be your API key.

  1. Add the following lines at the root level of your app-level build.gradle file:
def localPropertiesFile = rootProject.file("local.properties")
def localProperties = new Properties()
localProperties.load(new FileInputStream(localPropertiesFile))
  1. Pull the API into your project as a build config value by adding the following line to your app level build.gradle file in the android { defaultConfig { } } block:

def localPropertiesFile = rootProject.file("local.properties")
def localProperties = new Properties()
localProperties.load(new FileInputStream(localPropertiesFile))


android {
    // ...
    
    defaultConfig {
        // ...
        buildConfigField "String", "API_KEY", localProperties['apiKey']

    }
    
    // ...
    
}
  1. Sync Gradle and build the project. You can now access the key in your Java code with BuildConfig.API_KEY, for example:
String myApiKey = BuildConfig.API_KEY;
  1. You can add as many secret values as you'd like to your local.properties by following these steps. Give each one a unique reference, i.e. myApiKey2, BuildConfig.API_KEY_2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment