We've all been there. You're setting up a new service like Google Maps or Mapbox, you get the API key, and you just want to see it work. The quickest way? Plop it right into your code as a string. While it seems harmless, hardcoding API keys is one of the biggest security mistakes an Android developer can make.

This article will show you why it's so dangerous and give you a rock-solid, step-by-step method to secure your keys properly.

Why Hardcoding Keys is a Huge Problem

When you hardcode a key, you're embedding a secret password directly into your app's APK. An attacker can easily decompile your APK and find that key in plain text. They don't need to be a master hacker; free, automated tools can do it in seconds.

Bad: Hardcoding a key in a constants file
object Constants {
    const val MAPS_API_KEY = "AIzaSyB...THIS_IS_A_FAKE_KEY..._wCo"
}

Once an attacker has your key, the consequences can be severe:

  • Financial Abuse: If it's a key for a paid service like Google Maps Platform, attackers can use your key in their own high-traffic apps, leaving you with a massive bill.
  • Data Theft: If the key grants access to user data or other sensitive information, they can steal it.
  • Service Disruption: The service provider (like Google or Mapbox) will likely detect the fraudulent usage and revoke your key, breaking your app for all legitimate users.
Bottom line: Anything you put in your app's code should be considered public. Never put secrets there.

The Secure Solution: Gradle and `local.properties`

The correct way to handle API keys is to keep them out of your app's source code and inject them at build time. Here's the standard, industry-approved method.

Step 1: Store the Key in `local.properties`

Your Android project has a file named local.properties at the root. This file is not checked into version control (your .gitignore file already ignores it by default), making it the perfect place for local secrets.

Open local.properties and add your key:

Add your key to `local.properties`
# This file is not checked into version control
MAPS_API_KEY="AIzaSyB...YOUR_REAL_API_KEY_HERE..._wCo"

Step 2: Read the Key in `build.gradle`

Next, you need to tell Gradle to read this key from the properties file and make it available to your app. Open your app-level build.gradle.kts (or build.gradle) file.

First, load the properties file. Then, use buildConfigField to create a variable in the auto-generated BuildConfig class.

Read the key in `app/build.gradle.kts`
// 1. Load local.properties
val localProperties = java.util.Properties()
val localPropertiesFile = rootProject.file("local.properties")
if (localPropertiesFile.exists()) {
    localProperties.load(java.io.FileInputStream(localPropertiesFile))
}

android {
    // ... other config

    defaultConfig {
        // ... other config

        // 2. Create a BuildConfig field for the API key
        buildConfigField(
            "String",
            "MAPS_API_KEY",
            "\"${localProperties.getProperty("MAPS_API_KEY")}\""
        )
    }
    // ...
}

Step 3: Access the Key Securely in Your Code

After you sync your project with the Gradle files, Android Studio will generate a variable named MAPS_API_KEY in the BuildConfig class. You can now access it safely in your code.

Access the key via BuildConfig
// For example, in your Application class or Activity
val apiKey = BuildConfig.MAPS_API_KEY

// Now you can use this key to initialize an SDK
MapsInitializer.initialize(applicationContext, apiKey)

And that's it! Your key is now completely removed from your source code. If you push your code to GitHub, the key will not be there.

What About CI/CD?

For your automated build servers (like GitHub Actions), you won't have a local.properties file. In this case, you should store the API key as a secure environment variable or a secret. Your CI script can then read this environment variable and pass it to Gradle during the build process.

Taking a few minutes to set this up properly can save you from massive headaches, financial loss, and security breaches down the line. Check your projects today and make sure you're not leaving your keys out in the open!