Note
If you are using convention plugin for your project, solution at the bottom.
Tip
I would recommend creating another secrets.properties file just for ease of use, but this will work for any .properties file.
I will create another secrets.properties file in the project's root directory.
- Add your secrets in the file
secret_key=<value>
api_key=<value>- Inside
build.gradle.ktsfile (i.e. inside theandroidblock) you can load the key-value properties from the .properties file and access them as follows:
android { ...
defaultConfig { ...
val secretsFile = rootProject.file("secrets.properties")
val properties = Properties()
properties.load(secretsFile.inputStream())
// Return an empty string in case of property being null
val apiKey = properties.getProperty("api_key") ?: ""
// For accessing the property using BuildConfig
buildConfigField(
type = "String",
name = "API_KEY",
value = apiKey
)
}
// ...
}- Sync the project and access the keys through the
BuildConfigclass in your source code.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val apiKey = BuildConfig.API_KEY
...
}/**
* Created using Android Studio
* User: ashal
* Date: 8/22/2024
* Time: 11:16 AM
*/
class AndroidApplicationConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
....
extensions.configure<ApplicationExtension> {
configureKotlinAndroid(this)
defaultConfig.targetSdk = libs.versions.targetSdk.get().toInt()
val secretsFile = rootProject.file("secrets.properties")
val properties = Properties()
properties.load(secretsFile.inputStream())
defaultConfig.buildConfigField(
type = "String",
name = "API_KEY",
value = properties.loadProperty("api_key") ?: ""
)
}
}
}
}
Thanks!