I'm working on an Android application with Gradle as its build system.
My objective is to use a value (a package name) as an applicationId
:
productFlavors {
orange {
applicationId "com.fruits.android.orange"
// ...
But also to expose it via BuildConfig
so that Java code has access to it.
This access has to be from outside the flavor (namely, free version of the app needs to know the package name of the paid version so that it can prompt user for an upgrade in Play store).
So I'd like to do something like that:
productFlavors {
orange {
applicationId orangeProPackage
// ...
buildConfigField 'String', 'ORANGE_PRO_PACKAGE', "$orangeProPackage" // ?
Only I'm not sure how to define orangeProPackage
so that it's visible in the entire build.gradle and doesn't break the script.
Since there's a few different flavors, it would be best if I could somehow group all these constants like that (I guess?):
def proPackages = [
orange: "..."
apple: "..."
banana: "..."
]
and then refer to them in a clean and descriptive manner like proPackages.orange
etc.
The question is, how to accomplish that?
This is not a duplicate of Is it possible to declare a variable in Gradle usable in Java?
I've seen that question (and a few others). I know how to declare buildConfigFields, I already have plenty. My question is about reusing the same value as a buildConfigField
and applicationId
.
Local variables are declared with the def keyword. They are only visible in the scope where they have been declared. Local variables are a feature of the underlying Groovy language. Local variables are declared with the val keyword.
The "buildscript" configuration section is for gradle itself (i.e. changes to how gradle is able to perform the build). So this section will usually include the Android Gradle plugin.
Only I'm not sure how to define orangeProPackage so that it's visible in the entire build.gradle and doesn't break the script.
You could put it in gradle.properties
in your project root. Like other .properties
files, it's just a key-value store:
ORANGE_PRO_PACKAGE=com.morawski.awesomeapp
You then refer to it as a simple global string variable (ORANGE_PRO_PACKAGE
) in your build.gradle
:
buildConfigField 'String', 'ORANGE_PRO_PACKAGE', '"' + ORANGE_PRO_PACKAGE + '"'
it would be best if I could somehow group all these constants
Anything involving .properties
files won't handle that. There, you may be looking at defining globals in the top-level build.gradle
file just in plain Groovy code or something.
you could use extentions like this:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.6.10'
ext.app_version_code = 1010
ext.app_version_name = '1.0.1.0'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With