p0wl90
p0wl90

Reputation: 117

Access Gradle Command Line -P Variables in Android Build

First of all I am new to gradle so this might be a stupid question but I was not able to find a solution. I am trying to build a signed Android .apk file in the terminal and I want to use the command line in order to pass some arguments:

gradle assembleRelease -PkeyPw='secret123' -PstorePw='secret123' -PkeyAlias='My-Testkey' -PkeyLocation='/home/someUser/test-key.keystore'

Now I want to use these Variables inside the build.gradle file:

signingConfigs {
   release {
      storeFile $keyLocation
      storePassword $storePw
      keyAlias $keyAlias
      keyPassword $keyPw
   }
}

But they are null (Probably because it does not make any sense at all, but I did not find out how to do this).

Thanks for your help!

EDIT

I run the gradle build from java using the command

new ProcessBuilder().inheritIO.command(cmd).start 

and get the following error:

FAILURE: Build failed with an exception. 
* Where: 
Build file 'somePlace/app/build.gradle' line: 16 
* What went wrong: 
A problem occurred evaluating project ':app'. 
> Could not find property 'keyLocation' on project ':app'. 
* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Upvotes: 11

Views: 4961

Answers (2)

Opal
Opal

Reputation: 84756

All properties passed via -P switch are accessible via project variable. So it will be:

signingConfigs {
   release {
      storeFile project.keyLocation
      storePassword project.storePw
      keyAlias project.keyAlias
      keyPassword project.keyPw
   }
}

It's good idea to check if project has specified property before using it (to avoid problems):

signingConfigs {
   release {
      storeFile project.hasProperty('keyLocation') ? project.keyLocation : 'default'
      storePassword project.hasProperty('storePw') ? project.storePw : 'default'
      keyAlias project.hasProperty('keyAlias') ? project.keyAlias : 'default'
      keyPassword project.hasProperty('keyPw') ? project.keyPw : 'default'
   }
} 

Upvotes: 14

Justin Morris
Justin Morris

Reputation: 7329

An alternative way to handle this is to override the values in your build.gradle file.

./gradlew assembleRelease -Pandroid.injected.signing.store.file='/home/someUser/test-key.keystore' -Pandroid.injected.signing.store.password='secret123' -Pandroid.injected.signing.key.alias='My-Testkey' -Pandroid.injected.signing.key.password='secret123'

This requires no special code in your build.gradle file.

Upvotes: 2

Related Questions