Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a constant that is visible to all modules' build.gradle file?

I have a project that has multiple Modules - libraries and applications. Everytime a new version of Android comes out, I need to upgrade the targetSdk, compileSdk, buildToolsVersion, etc. for all the modules. A constant could help with this tedious work!

How could I define project-level constant that is visible to all module's build.gradle?

like image 329
Some Noob Student Avatar asked Jun 11 '15 01:06

Some Noob Student


2 Answers

The way I choose to do something similar is to create a properties file and then just read that for all my global variables. You can do this with java syntax:

Properties props = new Properties()
props.load(new FileInputStream("/path/file.properties"))

A more groovy like syntax is that's what you perfer is:

Properties props = new Properties()
File propsFile = new File('/usr/local/etc/test.properties')
props.load(propsFile.newDataInputStream())

That way, you may duplicate code in all your modules, but at least your problem is solved.

The second option is the use the ExtraPropertiesExtension I've personally never used it but according to the response to the question Android gradle build: how to set global variables it seems to do what you want.

UPDATE

If order to do this using the ExtraPropertiesExtension, in your <project base>/build.gradle add:

allprojects {
    repositories {
        jcenter()
    }
    //THIS IS WHAT YOU ARE ADDING
    project.ext {
        myprop = "HELLO WORLD";
        myversion = 5
    }
}

Then after a sync, in your build.gradle files for each module you can use this like so:

System.out.println(project.ext.myprop + " " + project.ext.myversion)
like image 159
Ali Avatar answered Sep 30 '22 19:09

Ali


For Android Studio users

You can define the constants in file "gradle.properties" and use them in module's gradle file.

gradle.properties

ANDROID_BUILD_MIN_SDK_VERSION = 16
ANDROID_BUILD_TARGET_SDK_VERSION= 20
ANDROID_BUILD_TOOLS_VERSION=20.0.0
ANDROID_BUILD_SDK_VERSION=20
ANDROID_BUILD_COMPILE_SDK_VERSION=21

module's build.gradle file

android {
    compileSdkVersion project.ANDROID_BUILD_COMPILE_SDK_VERSION=21
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        applicationId "com.abc.def"
        minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION
        targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
like image 23
zdd Avatar answered Sep 30 '22 18:09

zdd