I want to retreive key from local.properties
file that looks like :
sdk.dir=C\:\\Users\\i30mb1\\AppData\\Local\\Android\\Sdk
key="xxx"
and save this value in my BuildConfig.java
via gradle Kotlin DSL. And later get access to this field from my project.
Okay. I found solutions.
For Android Projects :
import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties
val key: String = gradleLocalProperties(rootDir, providers).getProperty("key")
NOTE: Prior to 2024 this was:
val key: String = gradleLocalProperties(rootDir).getProperty("key")
buildTypes
I write it:buildTypes {
getByName("debug") {
buildConfigField("String", "key", key)
}
}
override fun onCreate() {
super.onCreate()
val key = BuildConfig.key
}
For Kotlin Projects:
fun Project.getLocalProperty(key: String, file: String = "local.properties"): Any {
val properties = java.util.Properties()
val localProperties = File(file)
if (localProperties.isFile) {
java.io.InputStreamReader(java.io.FileInputStream(localProperties), Charsets.UTF_8).use { reader ->
properties.load(reader)
}
} else error("File from not found")
return properties.getProperty(key)
}
task("printKey") {
doLast {
val key = getLocalProperty("key")
println(key)
}
}