Gradle 一些方法记录

1、判断当前是否Release模式

2、获取当前是哪种Flavor

3、等待某个task开始执行前,dependsOn 某个任务

1、判断当前是否Release模式
//判断是否为release模式
def isReleaseBuildType() {
    boolean isReleaseTypes = false;
    for (String s : gradle.startParameter.taskNames) {
        if (s.equals(":app:assembleOfficialRelease") || s.equals("assembleOfficialRelease")) {
            isReleaseTypes = true;
            break;
        }
    }
    return isReleaseTypes;
}

2、获取当前是哪种Flavor
/**
 * 返回当前执行的是哪个变体
 * @return
 */
def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String taskReqStr = gradle.getStartParameter().getTaskRequests().toString()
    Pattern pattern
    if (taskReqStr.contains("assemble")) {
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    } else {
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
    }
    Matcher matcher = pattern.matcher(taskReqStr)
    if (matcher.find()) {
        String flavor = matcher.group(1)
        char[] c = flavor.toCharArray()
        c[0] = Character.toLowerCase(c[0])
        flavor = new String(c)
        return flavor
    } else {
        println "getCurrentFlavor:cannot_find_current_flavor"
        return ""
    }
}
3、等待某个task开始执行前,dependsOn 某个任务

project(":app") {
    Project project ->
        project.afterEvaluate {//等待app model的project完成后
            String taskReqStr = gradle.getStartParameter().getTaskRequests().toString()
            Pattern pattern
            if (taskReqStr.contains("assemble")) {
                pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
            } else {
                pattern = Pattern.compile("generate(\\w+)(Release|Debug)")
            }
            Matcher matcher = pattern.matcher(taskReqStr)
            if (matcher.find()) {//找到包含结构形如 assemblexxxxxxx的task
                Task buildTask = null;
                if (getCurrentFlavor().equals("gxx")){//只获取变体为gxx的
                    if (matcher.group().equals("assembleGxxDebug")){
                        buildTask = getBuildTask(project, ":app:assembleGxxDebug")
                    }else {
                        buildTask = getBuildTask(project, ":app:assembleGxxRelease")
                    }
                } 
                if (buildTask!=null){
                    buildTask.dependsOn(依赖的任务)
                }
            }
        }
}

/**
 * 获取该project对应的build任务
 * @param project
 * @return
 */
Task getBuildTask(Project project, String taskPath) {
    //获取该project管理task的容器
    TaskContainer taskContainer = project.getTasks()
    //拿到build的Task对象
    Task buildTask = taskContainer.getByPath(taskPath)
    return buildTask
}

你可能感兴趣的:(Gradle 一些方法记录)