In this article, we will take a step-by-step look at how to create a Gradle plugin and use it in an Android project.

IDE

To develop Gradle plug-ins, you have to decide which development environment to use. I myself have used Intellij IDEA and AndroidStudio for development, because AndroidStudio is based on Intellij, so there is not much difference.

However, as far as my personal preference is concerned, I prefer Intellij, because AndroidStudio is specially designed to develop Android, and there are many debugging buttons, it would be awkward to develop a pure Gradle plug-in project, so my judgment principle is as follows:

  • If it is a pure Gradle plugin project, use Intellij IDEA.
  • If you have a Gradle plugin project embedded in your Android project, such as a module for the plugin code, use AndroidStudio.

language

The dominant language for developing Gradle plugins is Groovy, because gradle is written in Groovy. A review of gradle plugin code written by third parties reveals that most of it is also written in Groovy.

In addition to Groovy, gradle plugins can be developed in other languages:

  • java
  • kotlin
  • Others are based on JVM languages

Since Groovy is jVM-based, the same JVM-based gradle plug-ins can also be written. But while Java and Kotlin are static languages, which means constant typing and strong turns, Groovy doesn’t have this problem as a dynamic language. So the rest of this article’s plug-in code is written in Groovy.

Let’s take a look at the requirements of the gradle plug-in we want to develop.

Requirements describe

To implement a plugin named IO. Helloworld. Myplugin, you need to implement the following functions:

  • Perform automatic Android configuration
    • Set minSdkVersion to 21
    • TargetSdkVersion is set to 26
    • Set compileSdkVersion to 29
    • Set buildToolsVersion to ‘29.0.2’
  • Register a Task namedmyTask.

Specific steps

  • Open Intellij IDEA and press File -> New -> Project to create a new project. In the “New Project” dialog, select Gradle on the left, and the “Additional Libraries and Frameworks” on the right, just select Groovy:

  • On the next screen, select groupId and ArtifactId that represent your plugin package, such as IO. Helloworld. Robot and gradleTools

    GroupId, artifactId, and Version make up the Id of our plug-in package, which another project needs to declare its dependencies if it wants to use our plug-in.

  • Then click “Next” -> “Finish” and the project structure should look something like this:

  • Add a gradle dependency to your project build.gradle script:

    
    dependencies {
        implementation gradleApi()
        ...
    }
    Copy the code

    Groovy dependencies are added to the IDE by default when you create a project:

    implementation 'org. Codehaus. Groovy: groovy - all: 2.3.11'
    Copy the code

    To prevent inconsistent versions of Groovy, it is best to have gradle automatically fetch the local groovy version instead.

    implementation localGroovy()
    Copy the code

    Then click gradle’s sync button to ensure that the IDE references the corresponding class.

  • Create package IO. Helloworld. Robot in groovy folder, same as groupId set earlier. Create a Groovy class MyPlugin under this package as follows:

    package io.helloworld.robot
    
    import org.gradle.api.Plugin
    import org.gradle.api.Project
    
    class MyPlugin implements Plugin<Project> {
        @Override
        void apply(Project project) {
            println("beginning of plugin 'MyPlugin'")}}Copy the code

    MyPlugin implements the Plugin interface, and this interface has a method apply(Project Project). This method will be called when our Plugin is applied in build.gradle. We add a line of code to this method that prints debugging information.

    The Plugin created here is for build.gradle, so the generic type of Plugin is Project. If used for settings.gradle, the generic type should be Settings.

    Now that our plug-in is created (albeit rudimentary), how do we get it to be used by Android projects? There are two more things you need to do: create a declaration file for the plug-in and publish the package containing the plug-in to the Maven repository.

  • Create a declaration file for the plug-in

    Create a meta-INF /gradle-plugins folder in the Resources folder where all the plugins declare files:

    The plugin declaration file is a configuration file with the suffix properties, and the filename is the plugin name, for example, io.helloworld.myPlugin. Associate the value of implementation-class in the file with the plugin class MyPlugin created above:

    implementation-class=io.helloworld.robot.MyPlugin
    Copy the code
  • Publish to the Maven repository

    Because the Maven repository is not the focus of this article, the package containing the plug-in will be published to the local repository for simplicity.

    To publish to a local repository, build.gradle needs to add the following code:

    apply plugin: 'maven-publish'
    
    publishing {
        publications {
            mavenPub(MavenPublication) {
                // This line indicates that the JAR package is included in the component to be published
                from components.java
                // Descriptive information
                pom {
                    name = 'Robot MyPlugin'
                    description = 'This is a test project for gradle plugin.'
                    url = 'http://www.helloworld.com'
                }
            }
        }
        repositories {
            maven {
                // The local repO address, where write your own address on your computer
                url = '/Users/zhanglei/projects/repo'}}}Copy the code

    Maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish: maven-publish

    Publish Tasks: Publish Tasks: Publish Tasks: Publish Tasks: Publish Tasks: Publish Tasks

    Double-click on the Task to publish the component. After executing the Task, you can see that the component has been published successfully under the address of the local repository:

    OK, all the preparation work is done and you are now ready to use the plug-in.

  • Use plug-ins in Android projects

    Since our plugin is configured with Android information, it will be used under the Module of application type. Open the build.gradle file under module in AndroidStudio and add the following code:

    // Use plugins
    apply plugin: 'io.helloworld.myplugin'
    buildscript {
        repositories {
            // Declare the address of the local repO
            maven {
                url '/Users/zhanglei/projects/repo'
            }
        }
        dependencies {
            // The declaration relies on the package we published to the local Maven repository above
            classpath 'the IO. The helloworld. Robot: gradletools: 1.0 the SNAPSHOT'}}Copy the code

    Because the plug-in is published in a local repository, declare the repository address in BuildScript.repositories. Then synchronize Gradle from AndroidStudio to see the log output from the debug code we just wrote in Apply () :

    Syncing gradle in AndroidStudio is slightly different from Intellij: click the following button:

    Ok, now that we have completed the development of the plug-in to use the plug-in path, we will complete the above “plug-in requirements” in the plug-in, let’s take a look at the first:

  • Plug-in function 1: Automatic configuration of Android

    • Set minSdkVersion to 21
    • TargetSdkVersion is set to 26
    • Set compileSdkVersion to 29
    • Set buildToolsVersion to 29.0.2

    Open the MyPlugin class in Intellij and add the following code to the apply() method:

    project.extensions.findByName('android').with {
        getProperty('defaultConfig').with {
            setProperty('minSdkVersion'.21)
            setProperty('targetSdkVersion'.26)
        }
        setProperty('compileSdkVersion'.29)
        setProperty('buildToolsVersion'.'29.0.2')}Copy the code

    Build. Gradle = build. Gradle = build. Gradle = build.

    android {
        defaultConfig {
            minSdkVersion 21
            targetSdkVersion 26
        }
        compileSdkVersion 29
        buildToolsVersion '29.0.2'
    }
    Copy the code

    Now that the first requirement is complete, let’s look at the second requirement.

  • Implement plugin function 2: register a Task myTask

    Open MyPlugin and add the following code to apply() :

    project.task('myTask') {
        group 'helloworld'
        description 'This is a task named myTask, created in myPlugin'
        doFirst {
            println("run in myTask it $it")}}Copy the code

    Here we create a Task named myTask and set the group, description, and its running code. As above, publish the plug-in to the local repository and synchronize the Android project gradle. You can see that the Android project already has myTask Task:

At this point, a Gradle plug-in with basic functionality has been developed. If you want to extend the functionality of this plug-in, you can continue to add code to the Apply () method. Because the apply() method takes project, all of the capabilities in build.gradle can be implemented here. You can also develop a new plugin in this project that puts some special Gradle processing logic.

Gradle plug-in development is briefly introduced here, because I am also learning while developing, it is inevitable that there are some wrong places, welcome your comments and corrections.