Android gradle build: how to set global variables

2019-01-22 06:19发布

问题:

How can I set a global variable that can be accessed from build.gradle and tasks?

回答1:

To set a global variable

project.ext.set("variableName", value)

To access it from anywhere in the project:

project.variableName

For instance:

project.ext.set("newVersionName", versionString)

and then...

println project.newVersionName

For more information see: http://www.gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html

EDIT: As commented by Dmitry, In new versions you can use the following shorthand:

project.ext.variableName = value


回答2:

The answer from Guy is excellent. I just want to add the practical code.

Example:

Put something like this in the Project build.gradle:

project.ext {
    minSdkVersion = 21
    targetSdkVersion = 23
}

And put something like this in the Module build.gradle to access it:

    defaultConfig {
        minSdkVersion.apiLevel project.minSdkVersion
        targetSdkVersion.apiLevel project.targetSdkVersion
    }


回答3:

you can also do this : lets say you want to add appcompat with the version 25.3.1 you can add a variable version_name in your project level build gradle

buildscript{
     ext.version_name = '25.3.1'
}

now you can add this to your application level build gradle and avoid any conflicts

compile "com.android.support:appcompat-v7:$version_name" compile "com.android.support:recyclerview-v7:$version_name" compile "com.android.support:design:$version_name"



回答4:

Additional, for dynamic global variables you can define global functions in the master build.gradle file:

First, define your function, for example for git branch:

def getGitBranch = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

In allProjects section set the variable:

allprojects {
    repositories {
        google()
        jcenter()
    }
    project.ext {
        gitBranch="\"${getGitBranch()}\""
    }
}

In your build.gradle files of your sub projects or android modules, get this variable like this:

android {
    compileSdkVersion project.mCompileSdkVersion.toInteger()
    defaultConfig {
        minSdkVersion project.mMinSdkVersion.toInteger()
        ...
        buildConfigField "String", "GitBranch", project.gitBranch
    }
    ...
}

Finally, you can use it in your code like this:

public static String getGitBranch() {
    return BuildConfig.GitBranch;
}