Groovy 101: How To Create Custom Gradle Tasks In Android Studio

saadnoorsalehin

saadnoor salehin

Posted on November 16, 2019

Groovy 101: How To Create Custom Gradle Tasks In Android Studio

For automating the build process, Android Studio uses Gradle, which is a build tool. Gradle uses Groovy-based DSL (Domain Specific Language) and Groovy is a powerful scripting language for Java platform.

Well, in summary, we need a little bit of familiarity with Groovy to work with Gradle. In this blog post, we will learn some hello world type Groovy, and then we will learn how to write custom tasks in Gradle with Groovy.

Variable Declaration:

def str = "hello world" yes, as simple as that.
Similarly we can declare lists and maps also,

def nameOfList = []
def nameOfMap = [:]
Enter fullscreen mode Exit fullscreen mode

Loops

Loops are very interesting, start.upto(end), that’s it.

Eg:

1.upto(5) {
 println "$it"
}
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

For iterating through lists and map, we can use every keyword.
Eg:

nameOfList.each { item ->
    println element
}
Enter fullscreen mode Exit fullscreen mode

Closures

In simple term, a block of code that acts like a function. This function can be assigned to a variable.

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable.

We will understand closure by running an example. Lets open android studio to play with Groovy. After opening the android studio, go to tools -> groovy console.

Type this code:

void doSomething(Closure closure) {
    closure.call()
}

doSomething {
    print “DID SOMETHING”
}
Enter fullscreen mode Exit fullscreen mode

Then run it, for running it click the green run button

Are these codes seems familiar? Your build.gradle file is full of these codes. Eg:

dataBinding {
    enabled = true
}
testOptions {
    animationsDisabled = true
}
Enter fullscreen mode Exit fullscreen mode

Now we will write a task in our build.gradle file, the task is to make a list of 10 numbers, (from 1 to 10), then print the list.

At the end of your app/build.gradle file, add this code:

task myFirstTask { task ->
    def list = []
    doFirst {
        1.upto(10){ val->
            list.add(val)
        }
    }
    doLast {
        list.each { item ->
            println(item)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code explains everything, still - myFirstTask is the task name, and into that we are defining our task.
doFirst and doLast is the syntax of Gradle to differentiate which portion will run first and which one will run last.

Now for executing this, in the terminal navigate to the project folder. and type:
./gradlew myFirstTask
If everything alright, you will see in your console:

> Task :app:myFirstTask
1
2
3
4
5
6
7
8
9
10
BUILD SUCCESSFUL in 4s
1 actionable task: 1 executed
Enter fullscreen mode Exit fullscreen mode

Okay, pretty boring , right?
Now let's​ do some interesting stuffs. I don’t like the name “app-debug.apk" every-time I build the project, and I am too lazy to navigate some subfolders to get this apk file, I want it in my desktop folder. Here is how, I will write the task.

task getDebugAppInDesktopFolder(dependsOn: 'assembleDebug') {
    doLast{
        def destination = "/Users/saadnoorsalehin/Desktop"
        def desiredName = "my-given-name"
        ext.apk = file("build/outputs/apk/debug/app-debug.apk")

        if (ext.apk.exists()) {
            copy {
                from ext.apk.absolutePath
                into destination
                rename { desiredName }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In the above code, the keyword dependsOn specify the dependencies tasks,
getDebugAppInDesktopFolder will require the execution of assembleDebug (the default task which will generate our debug apk) .

After running ./gradlew getDebugAppInDesktopFolder you will see your desired apk file in your desktop folder.

Thanks for reading, Groovy and Gradle both are very vast topic, it is impossible to make everything clear in a single blog post, but I hope you have gotten an idea how things work and how to play with them. If you have any query or feedback regarding this reach me at saadnoors9@gmail.com

💖 💪 🙅 🚩
saadnoorsalehin
saadnoor salehin

Posted on November 16, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related