STEP 1: Create a file named secrets.properties in the main folder (i.e below local.properties, app, build, gradle, README.md,etc.
STEP 2: Paste your API Key in secrets.properties (i.e GOOGLE_API_KEY, FACEBOOK_APP_ID, etc)
STEP 3: Sync the project or Rebuild.
STEP 4: Open build.gradle (app) and create a def function to access the key declared in the secrets.properties.
def getApiKey(){
def Properties props = new Properties()
props.load(new FileInputStream(new File('secrets.properties')))
return props['GOOGLE_MAPS_API_KEY']
}
STEP 5: Create a variable for the function getApiKey() in defaultConfig using manifestPlaceholders to use it in AndroidManifest.xml
defaultConfig {
defaultPublishConfig 'debug'
applicationId "YOUR_APPLICATION_ID"
minSdkVersion 19
targetSdkVersion 27
versionCode 1000
versionName '0.1.0'
manifestPlaceholders = [ GOOGLE_MAPS_API_KEY:getApiKey()]
}
You’re good to go. Now GOOGLE_MAPS_API_KEY variable is public and can be used in AndroidManifest.xml like below
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${GOOGLE_MAPS_API_KEY}" />
manifestPlaceholders — It helps to create a global variable that can be used only in AndroidManifest.xml
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt')
, 'proguard-rules.pro'
}
applicationVariants.all { variant ->
variant.buildConfigField "String", "GOOGLE_MAPS_API_KEY"
, "\""+getApiKey()+"\""
}
}
And, you can use GOOGLE_MAPS_API_KEY in Java or Kotlin classes like
BuildConfig.GOOGLE_MAPS_API_KEY
Finally, don’t forget to add secrets.properties to your .gitignore file.
Solution was gotten from This Medium post by Chandrasekar Kappusamy