【发布时间】:2020-03-31 16:12:55
【问题描述】:
我有一个配置模板文件,其中包含要根据当前构建风格(devDebug、prodRelease 等)填写的占位符。
我决定创建一个自定义 Gradle 任务并将其注入到正确运行的构建流程中,并在主资源文件夹 (main/res/raw) 中创建正确的配置文件。
我的目标是将生成的配置文件输出到构建文件夹的生成资源中,例如$buildDir/generated/res/myconfig/dev/debug/raw/config.json。我可以将输出的路径设置为类似它并创建文件,但是在尝试从代码访问它时我被卡住了。此外,AS 不会将文件夹 myconfig 识别为资源根目录(即使明确标记它)。我在这里想念什么?
这是完成这项工作的 Gradle 任务(它是 Kotlin):
fun configureMyConfiguration(variant: ApplicationVariant) {
getTasksByName(
"generate${variant.name.capitalize()}Resources",
true
).onEach { task ->
task.dependsOn(
task("${variant.name}ConfigureMyConfiguration") {
group = "MyApp"
description = "Configure my configuration"
doLast {
val configRoot = File("$buildDir/generated/myconfig/${variant.flavorName}/${variant.buildType.name}/res")
val templateFile = "$rootDir/app/config_template.json"
val configFile = File(configRoot, "raw/my_config.json")
val config = File(templateFile).readText()
.replace("\${foo}", "bar")
configFile.ensureParentDirsCreated()
configFile.createNewFile()
configFile.writeText(config)
project.android.sourceSets.getByName(variant.name) {
resources.srcDir(configRoot)
}
}
}
)
}
}
配置应用变体时调用设置任务的方法:
applicationVariants.all {
outputs.forEach {
configureMyConfiguration(this@all)
}
}
如您所见,文件夹和文件已在 build 文件夹中成功创建:
但是我想从代码中引用不起作用,因为生成的源没有被正确识别和组装。
我尝试将生成的文件夹添加到 gradle 文件的 android 块中的源集中 - 这样该文件夹被标记为资源根目录,但从代码中引用仍然无法正常工作。
【问题讨论】:
标签: android gradle android-resources android-build gradle-kotlin-dsl