同事突然問能不能在app.gradle中獲取buildConfigField設(shè)置的值扎谎,因為想要在輸出包名的時候炎功,帶上這里面的參數(shù)筒饰,所以就研究了一下
buildConfigField("int", "APP_PLATFORM", "1")
基本上都是Java的東西,運用反射取拿到指定的值砸讳,一開始就是通過一個值不斷的獲取內(nèi)部變量,知道get到一個變量就是
[APP_PLATFORM:ClassFieldImpl@21acde]
看到了勝利的曙光界牡,直接上代碼
這是輸出包名
applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
variant.outputs.all { output ->
def value = getBuildConfigFieldValue(variant,"APP_PLATFORM")
outputFileName = "${variant.flavorName}_${variant.buildType.name}_v${variant.versionName}_${value}.apk"
}
}
}
這是風味的代碼
// 渠道包定義
productFlavors {
test {
applicationId = "com.example.test"
versionCode 13000
versionName '1.3.0'
buildConfigField("int", "APP_PLATFORM", "1")
}
huawei {
applicationId = "com.example.huawei"
versionCode 13000
versionName '1.3.0'
buildConfigField("int", "APP_PLATFORM", "2")
}
獲取 buildConfigField的值的代碼,記得放在app.gradle的最外層
def static String getBuildConfigFieldValue(def variant, def fiedName) {
def properties = variant.productFlavors[0].properties
def name = properties.get("name")
if (name != variant.flavorName) {
return ""
}
def configs = properties.get("buildConfigFields")
def address = null
for (Map.Entry<String, Object> item : configs) {
def key = item.key
if (key == fiedName) {
address = item.value
}
}
if (address == null) return ""
def field = address.getClass().getDeclaredField("value")
field.setAccessible(true)
return field.get(address)
}
這樣就大功告成了