Android - Gradle assemble tasks

I’m currently struggling with a build process in gradle. My goal is to not have a specific java class in the final .apk for a specific flavor. The logic goes like this:

1.) before compiling my project delete MyClass.java and copy it to a temp folder

2.) after assembling the apk copy back MyClass.java to my original folder

3.) delete the temp folder

This happens only if I build a specific flavor, so it doesn’t happen for all build variants. My code works perfectly when I build only one flavor and one build variant e.g. assembleFlavorRelease, but if I wan’t to make my code work for multiple build types; if I run assembleFlavor it should build flavorDebug the same way it does flavorRelease. However my logic goes trough only the first time and after that it stops, so flavorDebug is build with MyClass and it shouldn’t be, while flavorRelease doesn’t include MyClass in the .apk because my code runs the first time.

Here is what the code looks like:

task copyResource << {
    copy {
        from 'src/main/java/MyClass.java'
        into 'src/temp'
    }
}

task deleteResource << {
    delete {
        'src/main/java/MyClass.java'
    }
}

task deleteTemp << {
    delete {
        'src/temp'
    }
}

task copyBackToSource << {
    copy {
        from 'src/temp/MyClass.java'
        into 'src/main/java'
    }
    deleteTemp.execute()
}

android.applicationVariants.all { variant ->
    if (variant.name.contains('flavor')) {
        deleteResource.dependsOn copyResource
        variant.javaCompile.dependsOn deleteResource
        variant.assemble.doLast {
            copyBackToSource.execute()
        }
    }
}

I think that the directories which I use in my code are somehow locked when trying to execute the whole process the second time?

Couldn’t you just exclude the file in question from the particular variant’s javaCompile task?

variant.javaCompile.exclude '**/SourceFileToExclude.java'

I just tried your solution and it works perfectly! Thank you!

You can also accomplish this inside of individual android.productFlavors blocks:

        android.productFlavors {
            create("flavor1") {
                deleteResource.dependsOn copyResource
                javaCompile.dependsOn deleteResource
                assemble.doLast {
                    copyBackToSource.execute()
                }
             }
             create("flavor2") {
                deleteResource.dependsOn copyResource
                javaCompile.dependsOn deleteResource
                assemble.doLast {
                    copyBackToSource.execute()
                }
              }
         }