如何过滤和执行特定的Gradle任务?

时间:2017-04-26 08:39:38

标签: android gradle gradle-task

我的Android项目配置了不同的产品口味:

productFlavors {
    devtracking {
        dimension trackingFlavorDimension
    }

    livetracking {
        dimension trackingFlavorDimension
    }

    stagingwebservice {
        dimension webserviceFlavorDimension
    }

    livewebservice {
        dimension webserviceFlavorDimension
    }

    playstore {
        dimension brandDimension
    }

    fdroid {
        dimension brandDimension
    }
}

如何编写仅为release版本构建devtracking构建的任务? “过滤器”准备就绪 - 我如何实际执行过滤的任务?请注意,现在“过滤器”已在配置时执行。

task assembleDevtrackingRelease {
    description "Assembles all Devtracking release builds."
    group = "Build"
    android.applicationVariants.all { variant ->
        if (variant.name.contains("DevtrackingRelease")) {
            println(variant.name)
            // TODO Execute this variant
        }
    }
}

2 个答案:

答案 0 :(得分:0)

task installDevtrackingReleaseFlavors() {
    android.applicationVariants.all { v ->
        if (v.name.endsWith('DevtrackingRelease')) {
            String name = v.name.capitalize()
            dependsOn "install$name"
        }
    }
}

答案 1 :(得分:0)

在Selvin和mirceanis的帮助下,我终于想出了这个解决方案:

// Creates a parent task for a set of sub tasks.
// Sub tasks are collected based on the given task name part.
def createVariantBatchTask(taskNamePart, taskPrefix = "assemble", taskGroup = "Build") {
    String taskName = "${taskPrefix}${taskNamePart.capitalize()}"
    Task task = tasks.create(taskName)
    task.description "${taskPrefix.capitalize()}s all $taskName builds."
    task.group taskGroup

    android.applicationVariants.all { variant ->
        if (variant.name.toLowerCase().contains(taskNamePart.toLowerCase())) {
            Task variantTask = tasks.findByName("${taskPrefix}${variant.name.capitalize()}")
            if (variantTask != null) {
                task.dependsOn variantTask
            }
        }
    }
}

createVariantBatchTask("devtrackingRelease")
createVariantBatchTask("devtrackingDebug")

可能的改进:转移到buildSrc中的自定义任务类。