Android gradle build: how to set global variables

后端 未结 4 1234
不思量自难忘°
不思量自难忘° 2020-12-13 16:57

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

4条回答
  •  粉色の甜心
    2020-12-13 17:37

    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;
    }
    

提交回复
热议问题