Android Groovy 脚本过渡为Kts脚本(2)

读取gradle.properties 到 BuildConfig

先看看gradle.properties

# -------Gradle--------
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
# -------Build parameters--------
# Values may be overridden in CI using gradlew "-Pname=value" param
apiBaseUrl="http://ws.audioscrobbler.com/2.0/"
# Typically we shouldn't store token in public repository, however this is just a sample project, so
# we can favour convenience (app can be compiled and launched after checkout) over security (each person who
# checkouts the project must generate own api key and change app configuration before running it).
# In real-live setup this key could be provided\overriden by CI.
apiToken="70696db59158cb100370ad30a7a705c1"
# -------Kotlin--------
# Kotlin code style for this project: "official" or "obsolete":
kotlin.code.style=official
kapt.use.worker.api=true
# Enable Compile Avoidance, which skips annotation processing if only method bodies are changed in dependencies
# To turn on Compile Avoidance we need to turn off AP discovery in compile path.
kapt.include.compile.classpath=false
# -------Android-------
android.useAndroidX=true
android.enableJetifier=true
android.nonTransitiveRClass=true

从Gradle项目属性中获取值,并将其设置为Android构建配置属性,例如:
设置中存在apiToken变量。gradle文件将作为BuildConfig进行访问。应用程序中的GRADLE_API_TOKEN。

自定义的一个比较重要的方法和Gradle提供的接口ApplicationDefaultConfig,利用kt的扩展函数

fun ApplicationDefaultConfig.buildConfigFieldFromGradleProperty(gradlePropertyName: String) {
    val propertyValue = project.properties[gradlePropertyName] as? String
    checkNotNull(propertyValue) { "Gradle property $gradlePropertyName is null" }

    val androidResourceName = "GRADLE_${gradlePropertyName.toSnakeCase()}".toUpperCase()
    buildConfigField("String", androidResourceName, propertyValue)
}

你可能感兴趣的:(Android Groovy 脚本过渡为Kts脚本(2))