Gradle: How to run custom task after an Android Li

2019-03-27 07:06发布

问题:

I have an Android Library, it's generating a debug.aar and a release.aar, I need to copy the release.aar to another folder as a reference to other part of the project.

What I've done now is in this Android Library build.gradle I defined a task:

task copyAARToCommonLibs(type: Copy) {
    from('../build/outputs/aar') {
        include '*-release.arr'
    }
    into '../SomeSampleApps/libs'
}

I'm trying to run this task after the arr is generated, which I assume is assembleRelease stage, so I tried do this in this build.gradle

assembleRelease.doLast{
   copyAARToCommonLibs
}

I build the overall project using

 gradle build

But this task is running at the very beginning of the whole process.

I also tried this:

 applicationVariants.all { variant ->
     variant.assemble.doLast {
         copyAARToCommonLibs
     }
 }

inside android{} property(I guess that's what it's called?) Running gradle build, got this error: Could not find property 'applicationVariants'

I then came across this snippet:

tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn copyAARToCommonLibs }

But it seems this makes the task to run after compiling, I don't know exactly how to modify this to run after assemble.

Could someone please correct me where I did wrong and how can I get this copy task work after the .arr file is generated?

回答1:

It seems that finalizedBy might be helpful.

assembleRelease.finalizedBy(copyAARToCommonLibs)

Mind the fact that in the following way you won't define a dependency:

assembleRelease.doLast {
   copyAARToCommonLibs
}

actually.. it does exactly nothing. You need to execute the task:

assembleRelease.doLast {
   copyAARToCommonLibs.execute()
}

but running task in the following way is discouraged and very bad practice.

You can also try:

assembleRelease.doLast {
   copy {
      from('../build/outputs/aar') {
        include '*-release.aar'
      }
      into '../AscendonSDKSamples/libs'
   }
}


回答2:

I went with finalizedBy() but had to include it within an afterEvaluate...

afterEvaluate {
    if (project.hasProperty("assembleFatRelease")) {
        assembleFatRelease.finalizedBy(crashlyticsUploadSymbolsFatRelease)
    } else {
        assembleFatDebug.finalizedBy(crashlyticsUploadSymbolsFatDebug)
    }
}

This worked well for automating the upload of native symbols to Fabric / Crashlytics.