Android 在.gradle中获取productFlavors中buildConfigField设置的值

同事突然问能不能在app.gradle中获取buildConfigField设置的值,因为想要在输出包名的时候,带上这里面的参数,所以就研究了一下

buildConfigField("int", "APP_PLATFORM", "1")

基本上都是Java的东西,运用反射取拿到指定的值,一开始就是通过一个值不断的获取内部变量,知道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 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)
}

这样就大功告成了

你可能感兴趣的:(Android 在.gradle中获取productFlavors中buildConfigField设置的值)