Search code examples
androidandroid-gradle-pluginandroid-build

How to add a Gradle task to an Android build


I would like to add a gradle task to my Android build under Android Studio. Various on-line documentation shows clearly how to create a task, but not where to place it in a build.gradle file and which one of them.

A simple, complete example would be perfect.

BTW, I'd like to add a pre-build task to prepare some data, and maybe a post-build task to do some verification/validation.


Solution

  • By trial-and-error and input from Martin Zeitler, I successfuly added pre- and post-build tasks to my build.gradle (app module) as shown below:

    This works perfectly.

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 26
        buildToolsVersion "27.0.3"
    
        defaultConfig {
            applicationId "MyPackage"
            minSdkVersion 11
            targetSdkVersion 26
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    
        dependencies {
          // My libraries here
        }
    
        // MY PREBUILD TASK
        task PreBuild {
            println "MY PRE-BUILD TASK"
        }
    
        // MY POSTBUILD TASK
        gradle.buildFinished {
            println "MY POST_BUILD TASK"
        }
    }