byte-sized adventures.

Hide API Key's in Android Studio (Relatively!)

01 Aug 2023

Step 0. Although as default feature, ‘.gitignore’ contains ‘local.properties’, make sure that statement exists.

First its needed to state that we are going to use build configuration.

android {
// .. Usual stuff

buildFeatures{buildConfig true}
}
android {
// .. Usual stuff

buildFeatures{buildConfig = true}
}

Then we are ready to state our variable(s) in build.gradle and local.properties

//buid.gradle
Properties properties = new Properties() 
properties.load(project.rootProject.file("local.properties").newDataInputStream()) 
  
buildConfigField
    "String", "API_KEY",    "\"${properties.getProperty("API_KEY")}\"" 
    "String", "API_PREFIX", "\"${properties.getProperty("API_PREFIX")}\""
#local.properties
API_KEY=your_api_key
API_PREFIX=https://api.com/

We are ready to go. Let’s build our project.

Now we can use these variables wherever its needed.

const val BASE_URL = "${BuildConfig.API_PREFIX}${BuildConfig.API_KEY}/"