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

时间:2014-09-09 07:41:54

标签: android android-gradle

我想基于当前的buildType在Android Gradle项目中动态添加依赖项。我知道我可以specify the buildType in the dependency

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

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

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

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

9 个答案:

答案 0 :(得分:12)

添加一个任务,该任务取决于调用后的每个assembleXxx任务和属性设置

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")
}

answer

获取了想法

答案 1 :(得分:9)

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

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

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

subprojects {
    android {
        dependencies.metaClass.allCompile { dependency ->
            buildTypes.each { buildType ->
                "${buildType.name}Compile" project(path: ":${dependency.name}", configuration: buildType.name)
            }
        }
    }
}

然后,您可以在Gradle模块中添加项目依赖项,如下所示:

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

答案 2 :(得分:9)

您可以使用

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

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

答案 3 :(得分:5)

这个很简单:

android {
    applicationVariants.all { variant ->
        variant.buildType.name // this is the value!
    }
}

编辑:显然在gradle更新的某个时刻,这不起作用,就像我在下面的评论中提到的那样。因此,我建议您查看其他选项。

答案 4 :(得分:3)

这是获得所需结果的最简单方法。您可以定义全局变量,然后更新它以便以后需要时使用。

// 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}"

}

答案 5 :(得分:0)

// 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变量中提取的内容的详细信息,请参阅Advance customization

现在你可以正确地将你的MyTask连接到链中。这样做也应该干净地处理同时构建多个风格,因为它为每个变体创建了一个新的MyTask实例。

答案 6 :(得分:-1)

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


请注意仅在特殊配置中使用以下声明 ,因为通常不应在代码中发生条件引用环境的情况。

build.gradle

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

答案 7 :(得分:-1)

基于Shooky's answerJLund's comment,这对我有用。我的应用程序build.gradle中将这些代码保存到最后:

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

只需将其命名为afterEvaluate。示例:

afterEvaluate {
    tasks.getByName("externalNativeBuild${ext.getCurrentBuildType()}")
         .dependsOn myOtherTask
}

很显然,gradle.startParameter有很多有关当前跑步的信息。看看doc

答案 8 :(得分:-2)

正在运行Gradle任务“ assembleRelease” ...