gradle execute task after build

Gradlebuild.gradle

Gradle Problem Overview


I am building my project with gradle, with the following build.gradle file:

project('a'){
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'application'

    buildDir = 'build'

    [compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
    repositories {
	    mavenCentral()
    }
    dependencies {
	    compile 'org.slf4j:slf4j-api:1.7.7'
    } 
}

When I input the gradle build command, I want gradle to execute a task after the build.

I found a mustRunAfter on the Internet, and I have tried a variety of ways but failed.

Please tell me if you know how.

Gradle Solutions


Solution 1 - Gradle

What you need is finalizedBy, see the following script:

apply plugin: 'java'

task finalize {
    doLast {
	   println('finally!')
    }
}

build.finalizedBy(finalize)

Here are the docs.

Solution 2 - Gradle

Nowadays you can use a BuildListener, it just works. Below is an example written in kotlin DSL

build.gradle.kts

plugins {
    id("com.android.application")
    id("kotlin-android")
    id("kotlin-kapt")
}

android {
    //[..]

    project.gradle.addBuildListener(object : BuildListener {
        override fun buildStarted(gradle: Gradle) {}

        override fun settingsEvaluated(settings: Settings) {}

        override fun projectsLoaded(gradle: Gradle) {}

        override fun projectsEvaluated(gradle: Gradle) {}

        override fun buildFinished(result: BuildResult) {
            
            // add what you need to do here
            println("finally!")
        }

    })
}

dependencies {
    //[...]
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjakeView Question on Stackoverflow
Solution 1 - GradleOpalView Answer on Stackoverflow
Solution 2 - Gradlelasec0203View Answer on Stackoverflow