我想通过在构建时从文件中读取属性来动态添加构建类型。因为有超过100种构建类型,所以我不在build.gradle文件中编写。
谁能帮帮我?
builde.gradle文件:
buildTypes{
release {
signingConfig signingConfigs.myConfig
runProguard true
zipAlign true
proguardFiles files('proguard.cfg', getDefaultProguardFile('proguard-android.txt'))
}
samsung {
initWith release
versionNameSuffix "samsung"
packageNameSuffix ".samsung"
}
google {
initWith release
versionNameSuffix "google"
packageNameSuffix ".google"
}
...
}
并修改每个构建清单:
android.applicationVariants.all { variant ->
def propertyList = variant.productFlavors*.name
propertyList.add(variant.buildType.name)
// read property from file
def variantProperties = new Properties()
propertyList.reverse().each { property ->
def propFile = "channel.properties"
try {
file(propFile).withReader { reader ->
def tmpProps = new Properties()
tmpProps.load(reader)
variantProperties.putAll(tmpProps)
}
} catch(e) {
println "[${variant.name}] Failed to load ${propFile}"
}
}
println "[${variant.name}] manifest properties: ${variantProperties}"
// default channel value is SinaDown
def defaultValue = "16"
def channel = variant.buildType.name
def value = variantProperties.getProperty("${channel}", defaultValue)
println "[Channel]: ${channel} [Value]: ${value}"
// modify AndroidManifest.xml
variant.processManifest.doLast {
copy {
from("${buildDir}/manifests") {
include "${variant.dirName}/AndroidManifest.xml"
}
into("${buildDir}/manifests/$variant.name")
// get the channel value
def channelValue = variantProperties.getProperty("${channel}", defaultValue)
println "[Channel]: ${channel} [Value]: ${channelValue}"
filter {
String line ->
line.replaceAll("<meta-data android:name=\"CHANNEL\" android:value=\".*\"/>",
"<meta-data android:name=\"CHANNEL\" android:value=\"${channelValue}\"/>")
}
// set the path to the modified Manifest:
def manifestPath = "${buildDir}/manifests/${variant.name}/${variant.dirName}/AndroidManifest.xml"
variant.processResources.manifestFile = file(manifestPath)
}
}
}
答案 0 :(得分:0)
我知道这个问题很老但我今天必须做类似的事情。 从yml文件中读取值以生成风格。 而且由于buildTypes和productFlavors都是NamedDomainObjectContainer,这也应该有效。
查看Inject Build Variables into the Manifest然后根据需要调整代码。
我的bluid.gradle文件类似于:
apply plugin: "pl.softmate.gradle-properties-yaml-plugin"
def configs = project.ext.properties.configs // configs from the .yml
android {
//...
configs.each { config ->
productFlavors.create(config.name, {
applicationId config.applicationId
// ...
})
}
我的yml文件:
---
configs:
- name: brand1
applicationId: com.app.brand1
- name: brand2
applicationId: com.app.brand2
---