Build / Gradle

Gradle Build – Part 8

Previously in this series we’ve looked at various aspects of the new Android Gradle build system. But what happens if the Android tools do not quite do what we require? In this article we’ll have a look at how we can extend and customise the Gradle build process.

gradle_logoA Gradle build consists of a series of tasks which are run in a particular sequence. When we have looked at the output from running our builds in previous articles, each of these tasks gets logged during the build process. The Android plugin defines a number of its own specific tasks, and it is these that are executed in sequence to perform an Android build.

We discussed previously how some aspects of what we covered in this series is specific to the Android plugin (such as build variants), and others are a feature of Gradle itself. Adding custom tasks falls in the latter category, and works independently of the Android plugin, although this does not stop us from customising the Android plugin build process as we shall see.

We can actually query Gradle for the tasks which have been defined for a particular build by executing the following command in the root project:

You can see the clean and assemble tasks that we have been invoking from the command line when performing builds. An interesting thing to note is that we can see tasks which have been created because of the custom build variants (Simple and Complex) which we added in the previous article. So adding build variants automatically created some related tasks.

Adding custom tasks is quite easy. The simplest way of creating a task is to create a Groovy task in build.gradle within our GradleTest project:

This is a really simple task which will simply print out a status string when it runs.

We can now see this in our tasks list:

We can now invoke this task from the command line:

We can see that the the task is running and printing its status string.

That’s all well and good, but defining standalone tasks don’t help us much. In the final article in this series we’ll look at how we can attach our task to the build lifecycle so it gets invoked as part of the build.

The source code for this article is available here.

© 2013 – 2014, Mark Allison. All rights reserved.

CC BY-NC-SA 4.0 Gradle Build – Part 8 by Styling Android is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Permissions beyond the scope of this license may be available at http://blog.stylingandroid.com/license-information.

Leave a Reply

Your email address will not be published. Required fields are marked *