You wouldn't want to check-in your API keys to the source code. Instead, you would like to embed them into your application generated by build tools using an external file that is ignored by your source controller. For Android there's already a standard file that's used for this purpose called local.properties.

AndroidManifest.xml is an xml file obviously and we cannot write scripts there. Instead, we can write a small script in build.gradle file, read api key from local.properties and assign it to a variable. AndroidManifest can read this variable from gradle file.

Let's say we want to add Google Maps API Key:

AndroidManifest.xml

<meta-data android:name="com.google.android.geo.API_KEY" android:value="${googleMapApiKey}"/>

googleMapApiKey is the variable that I want to create in build.gradle. Add below lines right before android{} section in your build.gradle(Module: app)

build.gradle

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def googleMapApiKey = properties.getProperty('google.map.key')

android {
}

This will look for "google.map.key" variable in local.properties file. So add your API key as below in local.properties file.

local.properties

## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
google.map.key = AIzaS*******-**********-*******

Sync your project with Gradle files and it should be all fine now.

Using Environment Variables

But you need to keep in mind that local.properties will not be checked into your source code. So, if you're using CI/CD (eg. appcenter), it will fail. local.properties is only good when you're a sole developer, generating apk in your local environment and uploading it manually.

But if you're in a team and using CI/CD the best way would be to use environment variables. Your AndroidManifest.xml will be the same

AndroidManifest.xml

<meta-data android:name="com.google.android.geo.API_KEY" android:value="${googleMapApiKey}"/>

But gradle.build will be like below:

build.gradle

def googleMapApiKey = System.getenv("googleMapApiKey")

android {
}

Now we need to set the environment variables. Open up your bash_profile file and

nano ~/.bash_profile

And paste your credentials.

export googleMapApiKey=AIzxxxxx-xxxxx-xxxx

It is important that you need to add this into ~/.bash_profile even if you're using zsh or other terminals. In my machine gradle sync did not read zsh config.

For Windows instead of export, you need to use SET  command

set googleMapApiKey=AIzxxxxx-xxxxx-xxxx