Step 1: Defining your key outside source code
Place the below line in your user-level gradle.properties
file.
MyAwesomeApp_ApiKey="your-api-key-goes-here"
I prefer to use this format <Project Name>_<Key Property Name>
so that I don’t mix up keys for different projects by mistake.
Step 2: Importing the key in your project
- Open your module-level
build.gradle
file (usually the one where you define dependencies for your app).
- Add your property in each of your build types.
- If you want to access the key from Java, then add it as a
buildConfigField
.
- If you want to access the key in your XML files (layouts and other resources), then add it as a
resValue
.
After doing that your build.gradle
might look like this
buildTypes {
debug {
buildConfigField 'String', "ApiKey", MyAwesomeApp_ApiKey
resValue 'string', "api_key", MyAwesomeApp_ApiKey
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField 'String', "ApiKey", MyAwesomeApp_ApiKey
resValue 'string', "api_key", MyAwesomeApp_ApiKey
}
}
Step 3: Using the key in your app's code
- In Java now you can simply replace all your uses of
API_SECRET_KEY
with BuildConfig.ApiKey
.
- In XML, you can refer to the key using
@string/api_key
.