groovy – How to define and use a constant in Gradle build script (Android)?-ThrowExceptions

Exception or error:

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.

How to solve:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *