如何在Android Gradle配置中获取当前的buildType

How to get current buildType in Android Gradle configuration

我想基于当前buildType在Android Gradle项目中动态添加依赖项。 我知道我可以在依赖项中指定buildType:

1
compile project(path: ':lib1', configuration: 'debug')

但是,如何使用当前的buildType来指定要导入的库的哪个变体,以便调试或发布的构建自动导入该库的调试或发布的变体? 我想要的是这样的东西(其中currentBuildType是一个变量,其中包含当前使用的buildType的名称):

1
compile project(path: ':lib1', configuration: currentBuildType)

我要导入的库项目已设置publishNonDefault true,因此所有buildTypes均已发布。


您可以使用

if(gradle.startParameter.taskNames.contains("assembleExample")) {
// do stuff
}

该变量将在评估buildConfig块之前设置


在Gradle的配置阶段,我找不到一种干净的方法来获取当前的构建类型。相反,我像这样分别为每种构建类型定义依赖项:

1
2
debugCompile project(path: ':lib1', configuration: 'debug')
releaseCompile project(path: ':lib1', configuration: 'release')

如果您有许多构建类型和许多项目依赖项,则可能会变得非常冗长,但是可以添加一个函数使该依赖项成为单行。您需要将此添加到您的主要Gradle构建文件中:

1
2
3
4
5
6
7
8
9
subprojects {
    android {
        dependencies.metaClass.allCompile { dependency ->
            buildTypes.each { buildType ->
               "${buildType.name}Compile" project(path:":${dependency.name}", configuration: buildType.name)
            }
        }
    }
}

然后,您可以像这样在Gradle模块中添加项目依赖项:

1
allCompile project(':lib1')

如果还使用构建样式,则必须调整解决方案。请参阅此链接以获取有关功能的文档:
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication

请注意,Android团队正在努力改善此行为:
https://code.google.com/p/android/issues/detail?id=52962


添加一个依赖于每个assembleXxx任务和调用后设置的属性的任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ext {
    currentConfig =""
}
task generateConfigProperty(dependsOn: 'installDebug') {

    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->

            def taskName ="taskindicate$output.name"
            task"$taskName"() << {
                project.ext.set("currentConfig","$output.name")
            }
            output.assemble.dependsOn"taskindicate$output.name"
        }
    }

}

task getConfig(dependsOn: ['installDebug', 'generateConfigProperty']) << {
    println("My config is $currentConfig")
}

从答案中得到灵感


这很简单:

1
2
3
4
5
android {
    applicationVariants.all { variant ->
        variant.buildType.name // this is the value!
    }
}

编辑:显然在某个时候使用gradle update,这不起作用,正如我在下面的评论中提到的那样。因此,我建议您检查其他选项。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// declare a custom task class so you can reuse it for the different
// variants
class MyTask extends DefaultTask {
     String mVariantName;
     public void setVariantName(String variant) {mVariantName = variant;}
     public String getVariantName() { return mVariantName; }
     @TaskAction
     void action(){
        // do stuff
     }
}

// put this after your `android{}` block.
android.applicationVariants.all { variant ->
    def taskName ="myTask_$variant.name"
    task"$taskName"(type: MyTask) << {
        // you can setup this task to various info regarding
        // variant
        variantName = variant.name
    }
    variant.assemble.dependsOn (taskName)
}

有关可以从variant变量提取的内容的更多详细信息,请参见高级定制。

现在您将正确地将MyTask连接到链中。以这种方式执行此操作还应一次完成所有风味的构建,因为它会为每个变体创建MyTask的新实例。


根据Shooky的回答和JLund的评论,这对我有用。我在我的应用程序build.gradle中将这个代码写到最后:

1
2
3
4
5
ext.getCurrentBuildType = {
    def isDebug = gradle.startParameter.taskRequests.any {
                            it.args.any { it.contains("Debug") } }
    return isDebug ?"Debug" :"Release"
}

只需将其命名为afterEvaluate。例:

1
2
3
4
afterEvaluate {
    tasks.getByName("externalNativeBuild${ext.getCurrentBuildType()}")
         .dependsOn myOtherTask
}

显然,gradle.startParameter具有有关当前运行的大量信息。看一下文档。


基于环境执行特定代码的想法应该通过依赖注入。


请考虑将以下声明仅用于特殊配置,因为通常不应在代码中出现条件引用环境的情况。

build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
android {

    def TRUE ="true"
    def FALSE ="false"
    def IS_DEV ="IS_DEV"
    def IS_RELEASE ="IS_RELEASE"

    defaultConfig {
        //...
        buildConfigField BOOLEAN, IS_DEV, FALSE
        buildConfigField BOOLEAN, IS_RELEASE, FALSE
    }

    buildTypes {
        debug {
            buildConfigField BOOLEAN, IS_DEV, TRUE
        }
        release {
            buildConfigField BOOLEAN, IS_RELEASE, TRUE
        }
    }

}

GL


这是获得所需结果的最简单方法。您定义全局变量,然后对其进行更新以在以后需要的地方使用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// query git for the SHA, Tag and commit count. Use these to automate versioning.
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
//def gitTag = 'git describe --tags'.execute([], project.rootDir).text.trim()
def gitCommitCount = 100 +
        Integer.parseInt('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())
def buildTime = new Date().format("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))

def versionMajor = 1
def versionMinor = 5
def versionPatch = 2
def versionBuild = 0 // bump for dogfood builds, public betas, etc.

def buildType // define here to update in loop

android {

    applicationVariants.all { variant ->
        buildType = variant.buildType.name // sets the current build type
    }

    defaultConfig {
        applicationId"com.example"
        minSdkVersion 19
        targetSdkVersion 25
        vectorDrawables.useSupportLibrary = true

        versionCode gitCommitCount
        versionName"${versionMajor}.${versionMinor}.${versionPatch}.${versionBuild}"
        versionNameSuffix"-${buildType}-build-${buildTime}"

}