Search code examples
androidgradlecommand-lineparametersarguments

How to Dynamically Create or Set a BuildConfigField for Android Studio Using Gradle Command Line


I know how to create a buildConfigField variable and set its value in my build.gradle file. E.g. buildConfigField 'String', 'BUILD_VALUE', 'HELLO WORLD'.

I also know how to pass in an argument from gradle command line via task. For instance, if I do ./gradleW propertyTypes -Dargs=test1 -Pargs=test2 in terminal and have the following in my build.gradle:

task propertyTypes(){
    doLast{
        if (project.hasProperty("args")) {
            println "Project property ["+project.getProperty("args")+"]"
        }
        println "System property ["+System.getProperty("args")+"]"
    }
}

it will output test2 and test1 to terminal.

However, I don't know how to put them together. I want to be able to pass in an argument (e.g. "Hello World") via the gradle commandline and then have that set as a buildConfigField for use in the program itself. When I try though, either task doesn't know what a buildConfigField is or the buildConfigField doesn't know the properties passed into the task.

Any insight on how I can make this work?


Solution

  • This answer worked for me:

    https://stackoverflow.com/a/65150777/5026136

    To paraphrase:

    Step 1: Create a variable to hold the default value in the gradle.properties file

    MY_VAR=defaultValue

    Step 2: Create a buildConfigField variable called [VAR_NAME] in the app's build.gradle file inside the android->defaultconfig block. For its value, give it the variable you put in gradle.properties using the syntax below:

    android {
        defaultConfig {
            buildConfigField "String", "VAR_NAME", "\"$MY_VAR\""
        }
    

    Step 3: Rebuild the project. (Until you do, you won't be able to access the new BuildConfig variable in your code.)

    Step 4: Use the BuildConfig.VAR_NAME variable in your app's code as desired.

    Step 5: Pass a new value for the variable via command line by adding the following flag to your gradlew command line:

    -P MY_VAR=new_value

    where new_value is whatever you decide and MY_VAR is the name you put in your gradle.properties file.


    As an added bonus, you can check that you are indeed able to pass in a value via command line and have it update correctly by adding the following to your app's build.gradle (just prior to the android block):

    task output { println "\"$MY_VAR\"" }

    (Note that "output" is just a name for the task --- you can call it anything)

    Then if you run ./gradleW output in terminal, it will print the default value for MY_VAR as you've set it in gradle.properties.

    If instead you run ./gradleW output -P MY_VAR=new_val then it will print the updated value!