Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a variable in Gradle usable in Java?

Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time. Just like a pre-processor macros in C/C++...

An example of declaration would be something like that ... :

android {     debug {         A_VAR_RETRIEVABLE_IN_JAVA = 42     }     release {         A_VAR_RETRIEVABLE_IN_JAVA = 42+52     } } 

Is there a way to do something like that ?

like image 924
klefevre Avatar asked Jun 19 '13 17:06

klefevre


2 Answers

Here are two ways to pass value from Gradle to use in Java;

Generate Java Constants

android {     buildTypes {         debug {             buildConfigField "int", "FOO", "42"             buildConfigField "String", "FOO_STRING", "\"foo\""             buildConfigField "boolean", "LOG", "true"         }          release {             buildConfigField "int", "FOO", "52"             buildConfigField "String", "FOO_STRING", "\"bar\""             buildConfigField "boolean", "LOG", "false"         }     } } 

You can access them with BuildConfig.FOO

Generate Android resources

android {     buildTypes {         debug{             resValue "string", "app_name", "My App Name Debug"         }         release {             resValue "string", "app_name", "My App Name"         }     } } 

You can access them in the usual way with @string/app_name or R.string.app_name

like image 177
rciovati Avatar answered Oct 06 '22 02:10

rciovati


An example of usage an Api App Key in an Android application (Java and XML)

gradle.properties

AppKey="XXXX-XXXX" 

build.gradle

buildTypes { //...     buildTypes.each {         it.buildConfigField 'String', 'APP_KEY_1', AppKey         it.resValue 'string', 'APP_KEY_2', AppKey     } } 

Usage in java code

Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));  BuildConfig.APP_KEY_1 

Usage in xml code

<data android:scheme="@string/APP_KEY_2" /> 
  • Link to an example of Api App Key usage in an Android application
  • Using String Constants Generated by Gradle Build Configurations
like image 31
Denis Avatar answered Oct 06 '22 02:10

Denis