Image Credit: https://gradle.org/

Write a custom Gradle Plugin (Part 2)

Custom Gradle task with configuration

In the previous blog, I have explained how to create a simple Gradle plugin. Here I’ll be discussing in more depth about Gradle task and how to configure parameters to the plugin during apply.

Let’s take an example where I’ll be creating a resource(XML) file from JSON for an android app.

First, we’ll create a custom Gradle task and add it to the plugin.

Now we’ll have to add this task to the plugin.

Now trigger the uploadArchive task or execute from the terminal by using the below command:

Now run the SimpleTask from the app, we will get the below output.

Now let’s go one step further and read the JSON file and create the resource file from this task.

First, let's create a resource.json file and place it inside the app directory (This is just for demo. You can specify any path).

Now we’ll be parsing this JSON and converting it to a color resource file. In order to achieve this, we’ll need to make changes in our SimpleTask. Here we need two main things:

  1. Input file path (resource.json)
  2. Output file path (resource.xml)

Now our SimpleTask will look like this:

Now we’ll have to pass both the file's path to SimpleTask.

Again export the plugin with new code changes and run the SimpleTask from the app. Now resource.xml will be added to app/src/main/res/values directory.

To pass the file’s path to the plugin we’ll have to add an extension for the plugin. I have created a class PluginConfig for that and add as an extension to the plugin.

Add as an extension to the plugin

Now let's pass the plugin config from the app. For this add below lines of code in app’s build.gradle (module-level):

To retrieve this config in the plugin, our final SamplePlugin & SimpleTask class will look like this:

The below lines of code is to retrieve the value of inputFile in the plugin which being pass from our app’s build.gradle (module-level).

We can group all the tasks in place by using the below code.

Now if we check the app project the tasks will be grouped like below:

Now if we run this task we’ll see the new files which will be added to the below path directory:

Thanks for reading this. In the next part, I’ll be talking about Unit & Functional testing of the plugin.

Android Developer, Bangalore

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store