Home » Android » Passing -P parameters to gradle from android studio

Passing -P parameters to gradle from android studio

Posted by: admin April 23, 2020 Leave a comment

Questions:

Is there a functionality inside android studio to do things like this.
Basically my gradle script reads parameter named version based on which it sets dependency version of a certain library.
So when I do gradlew -Pversion=‘1.2.3′ I get this string inside gradle. But this only works if I invoke gradle from console.

Is there a way to pass parameters to gradle when started using configuration for project inside Android Studio (pressing little play triangle)?

NOTE:I did find Gradle VM options and Script prameters under default configs but adding -Pversion=‘1.2.3′ there doesn’t seem to have an effect.

How to&Answers:

In order to provide parameter to run option of Android Studio you should setup them under AndroidStudios Compile Preferences

AndroidStudio > Preferences…

Under Compiler: ComandLineOptions
enter image description here

Answer:

Run > Edit Configurations..

enter image description here

Replace “abcdef” in Script parameters by your params.

Answer:

For example let’s try to pass server base endpoint while building project. First we need to define a method which gets url and sets it

def serverUrl = "https://mydefaulturl.com"
task(runProgram){
   if(project.hasProperty("url")){
       serverUrl = url;
   }
}

In your buildTypes create your base url with this value:

debug{
   buildConfigField("java.lang.String","BASE_URL","$serverUrl")
}

Now we can pass debug build an url and use it.

You can build your project from terminal with the command below:

./gradlew installDebug task runProgram '-Purl="https://yournewurl.com"'

Answer:

Put version="1.2.3" in gradle.properties or under

buildscript {
    ext{
        version="1.2.3"
    }
...
}