I\'m wondering how to add dependency to specific productFlavor and buildType in gradle.
For example I have productFlavor free
and build type release
Looks like now in version 1 of the android gradle plugin and gradle 2.2+, you can do this with a configuration:
configurations {
freeReleaseCompile
}
android {
...
productFlavors {
free {
...
}
}
}
dependencies {
freeReleaseCompile('myLib@aar')
}
Reference: https://groups.google.com/forum/#!msg/adt-dev/E2H_rNyO6-o/h-zFJso-ncoJ
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.
There is built-in support for flavor and buildType dependencies.
dependencies {
flavor1Compile "..."
freeReleaseCompile "..."
}
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Sourcesets-and-Dependencies
Here is another way that I used:
tasks.withType(JavaCompile) {
compileTask ->
def dependedTaskName = "dependedTask_";
if(compileTask.name.contains('Release') {
dependedTaskName += "Release";
}
createTask(dependedTaskName, Exec) {
........
}
compileTask.dependsOn ndkBuildTaskName
}
Another way:
tasks.whenTaskAdded { task ->
if (task.name == 'generateReleaseBuildTypeBuildConfig') {
task.dependsOn doSomethingForReleaseBuild
}
}
The 1st method is dynamic while the second one is simpler.
Muschko's answer didn't work for me, so this is my solution, written and posted by me here
Define the task that should only be executed on a specific buildType/variant/flavor
task doSomethingOnWhenBuildProductionRelease << {
//code
}
It's important to use the "<<" syntax or else the task will automatically be called every time.
Dynamically set the dependency when the tasks are added by gradle
tasks.whenTaskAdded { task ->
if (task.name == 'assembleProductionRelease') {
task.dependsOn doSomethingOnWhenBuildProductionRelease
}
}
These task are generated dynamically based on your Android plugin configuration. At the time of configuration they are not available to you yet. You can defer the creation of your task in two ways:
Wait until the project is evaluated.
afterEvaluate {
task yourTask(dependsOn: assembleFreeRelease) {
println "Your task"
}
}
Lazily declaring the task dependency as String.
task yourTask(dependsOn: 'assembleFreeRelease') {
println "Your task"
}