7

The following task (in build.gradle of an app's module) seems to run always before the apk is produced:

android.applicationVariants.all { variant ->
    if (variant.buildType.name == 'release') {
            def releaseBuildTask = tasks.create(name: "debug") {
            println("....................  test   ..............................")
        }
        releaseBuildTask.mustRunAfter variant.assemble
    }
}

Could anyone offer a tip on how to run a task after the apks are produced?

Hong
  • 17,643
  • 21
  • 81
  • 142

3 Answers3

18

Android tasks are typically created in the "afterEvaluate" phase. Starting from gradle 2.2, those tasks also include "assembleDebug" and "assembleRelease". To access such tasks, the user will need to use an afterEvaluate closure:

afterEvaluate { assembleDebug.dependsOn someTask }

source: https://code.google.com/p/android/issues/detail?id=219732#c32

Pol
  • 482
  • 3
  • 11
11

I found a solution that works, to copy the release APK into the project root automatically on build completion.

    android {
        ...
        task copyReleaseApk(type: Copy) {
            from 'build/outputs/apk'
            into '..' // Into the project root, one level above the app folder
            include '**/*release.apk'
        }

        afterEvaluate {
            packageRelease.finalizedBy(copyReleaseApk)
        }
}
Ashwin
  • 12,691
  • 31
  • 118
  • 190
Ollie C
  • 28,313
  • 34
  • 134
  • 217
10

try add this in you app/build.gradle

assembleDebug.doLast {
    android.applicationVariants.all { variant ->
        if (variant.buildType.name == 'release') {
            def releaseBuildTask = tasks.create(name: "debug") {
                println("....................  test   ..............................")
            }
            releaseBuildTask.mustRunAfter variant.assemble
        }
    }
    println "build finished"
}

invoke the build command and specify the task assembleDebug

./gradlew assembleDebug

alijandro
  • 11,627
  • 2
  • 58
  • 74
  • Thanks a lot for the answer. I migrated to Android Studio from Eclipse yesterday. The difference is quite significant. – Hong Dec 31 '14 at 02:43
  • Does this have to invoked via the command line? Will the `doLast` block still execute if we're using the green run button in android studio? – 11m0 Apr 19 '18 at 15:39
  • @11m0 run the task from command line or android studio is totally the same. – alijandro Oct 23 '18 at 01:56
  • You must put this command inside afterEvaluate starting from gradle 2.2 https://stackoverflow.com/a/52915218/8942811 – Bek Nov 26 '20 at 06:22
  • Android tasks are typically created in the "afterEvaluate" phase. Starting from 2.2, those tasks also include "assembleDebug" and "assembleRelease". To access such tasks, the user will need to use an afterEvaluate closure – Bek Nov 26 '20 at 06:24