Groovy 101: How To Create Custom Gradle Tasks In Android Studio
Tags: groovy, android, gradle, devops
Published: 2019-11-16 18:41:31


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 = [:]
```
**Loops**  
Loops are very interesting, `start.upto(end)`, that’s it.

Eg:
```
1.upto(5) {
 println "$it"
}
```
Output: 
```
1
2
3
4
5
```
For iterating through lists and map, we can use `every` keyword.
Eg: 
```
nameOfList.each { item ->
	println element
}
```
**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.
![](https://thepracticaldev.s3.amazonaws.com/i/krrb5ptmc32adey39hok.png)
Type this code: 
```
void doSomething(Closure closure) {
    closure.call()
}

doSomething {
    print “DID SOMETHING”
}
``` 
Then run it, for running it click the green run button 
![](https://thepracticaldev.s3.amazonaws.com/i/qcux1atltlehbadvonpc.png)

Are these codes seems familiar? Your `build.gradle` file is full of these codes.  Eg: 
``` groovy
dataBinding {
    enabled = true
}
testOptions {
    animationsDisabled = true
}
```

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:
```groovy
task myFirstTask { task ->
    def list = []
    doFirst {
        1.upto(10){ val->
            list.add(val)
        }
    }
    doLast {
        list.each { item ->
            println(item)
        }
    }
}
```
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:
```groovy
> Task :app:myFirstTask
1
2
3
4
5
6
7
8
9
10
BUILD SUCCESSFUL in 4s
1 actionable task: 1 executed
```

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.

```groovy
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 }
            }
        }
    }
}
```

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