是否可以在 gradle productFlavors 中声明一个变量并在 Java 中使用它?

Is it possible to declare a variable in gradle productFlavors and use it in Java?

我知道在buildTypes可以申报,但我想在productFlavors申报。

像这样:

productFlavors {
    f1 {
        some_variable: "v_f1"
    }
    f2 {
        some_variable: "v_f2"
    }
}

类似问题:

Is it possible to declare a variable in Gradle usable in Java?

当然 .

通过BuildConfig.some_variable访问它。

您将获得变量值 according to the build variant .

是的,像这样:

productFlavors {
    f1 {
        buildConfigField "boolean", "aBoolean", "true"    
        buildConfigField "String", "aString", "foo"
    }
    f2 {
        buildConfigField "boolean", "aBoolean", "false"    
        buildConfigField "String", "aString", "bar"
    }
}

然后在运行时您可以像这样访问它们:

if (BuildConfig.aBoolean) {
    // do something
}