In Android/Gradle how to define a task that only runs when building specific buildType/buildVariant/productFlavor (v0.10+)

谁说我不能喝 提交于 2019-11-29 21:31:25

Here is a full example on how to do this inspired by this post: (android plugin v.0.9.2 and gradle 1.11 at the time of writing)

We are going to define a task that only runs when we build a "debugCustomBuildType"

android {
    ...
    buildTypes {
        debugCustomBuildType {
            //config
        }
   }
}

Define the task that should only be executed on a specific builtType/variant/flavor

task doSomethingOnWhenBuildDebugCustom {
    doLast {
       //task action
    }
}

Dynamically set the dependency when the tasks are added by gradle

tasks.whenTaskAdded { task ->
    if (task.name == 'generateDebugCustomBuildTypeBuildConfig') {
        task.dependsOn doSomethingOnWhenBuildDebugCustom 
    }
}

Here we use the "generateBuildConfig" task, but you can use any task that works for you (also see official docs)

  • processManifest
  • aidlCompile
  • renderscriptCompile
  • mergeResourcess.
  • mergeAssets
  • processResources
  • generateBuildConfig
  • javaCompile
  • processJavaResources
  • assemble

Don't forget to use the buildTypeSpecific task (generateBuildConfig vs. generateDebugCustomBuildTypeBuildConfig)

And that's it. It's a shame this workaround isn't well documented because for me this seems like one of the simplest requirements for a build script.

I achieved it like this:

android {
    ext.addDependency = {
        task, flavor, dependency ->
            def taskName = task.name.toLowerCase(Locale.US)
            if (taskName.indexOf(flavor.toLowerCase(Locale.US)) >= 0) {
                task.dependsOn dependency
            }
    }

    productFlavors {
        production {
        }
        other
    }

    task theProductionTask << {
        println('only in production')
    }

    tasks.withType(JavaCompile) {
        compileTask -> addDependency compileTask, "production", theProductionTask
    }
}

To be frank, I don't which locale is used to generate names for compile taks so toLowerCase(Locale.US) may be counterproductive.

This is the only solution that worked for me:

afterEvaluate {
    if (project.hasProperty("preReleaseBuild")){
        tasks.preReleaseBuild.dependsOn bundleJSRelease
    } else {
        tasks.preDebugBuild.dependsOn bundleJSDebug
    }
}
tasks.whenTaskAdded { task ->
    if (task.name.contains("assembleRelease")) {
        task.getDependsOn().add({
            // add your logic here
        })
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!