Skip to content

Instantly share code, notes, and snippets.

@loftywaif002
Last active June 4, 2024 13:03
Show Gist options
  • Save loftywaif002/f2ebe2024ad73d6a579285dcba250465 to your computer and use it in GitHub Desktop.
Save loftywaif002/f2ebe2024ad73d6a579285dcba250465 to your computer and use it in GitHub Desktop.
Hiding Api Keys in Anroid

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
@tuulingo
Copy link

Thank you! Finally found a simple guide that didn't waste 10 minutes of my life. Looked on Google and Youtube and followed their instructions, but couldn't my API_KEY to work.

this is not working also for me

Did you figure it out, or found another way?

@SaidmurodTurdiyevDeveloper

how can i do this it on if my gradle will kotlin not groovy

@Mohamed-Ayad902
Copy link

how can i do this it on if my gradle will kotlin not groovy

did you found a solution ?

@pavelsust
Copy link

This is not a solution. If you build your application & decompile it you will find api key in BuildConfig file.

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