Android gradle build: how to set global variables

拜拜、爱过 提交于 2019-11-28 19:05:42

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

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
    }

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"

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!