Gradle plugin concept

Gradle is a build tool that makes building projects more automatic, but it is just an execution environment that provides the basic framework. The real build behavior is not provided by Gradle. Gradle is responsible for finding all the tasks that need to be executed at runtime.

The tasks mentioned above can be created in two ways. One is manually created, such as compiling the project Java code in a custom task. The second is through plug-ins, similar code is encapsulated, almost all functions are provided in the form of plug-ins. Plug-ins encapsulate or provide tasks that Gradle needs to run. Once you rely on a plug-in in your project, you can reuse the build behavior provided by that plug-in.

The Android Gradle plugin is based on the Java plugin extension. On the basis of compiling Java code, it adds the function of compiling resources and packaging APK.

The main content of this paper is shown in the figure.

Gradle plugin classification

Gradle plug-ins come in two types: binary plug-ins and script plug-ins.

Script plug-ins: Lightweight, standalone Gradle scripts. The build.gradle script can be used to further configure or supplement the configuration of the project. It can be stored in the project directory or in the address of a remote server.

Binary plug-in: implemented plugin interface, can exist in a separate compilation script, can also be maintained as an independent project, external release into plug-in Jar package, such as Android plug-in.

The original form of a plug-in is a script plug-in. When the code in the script needs to be reused, the script plug-in can be packaged as a binary plug-in, which can be easily shared among different teams or projects.

2.1 Usage of binary plug-ins

Binary plug-in usage is divided into three parts: declare the ID and version number of the plug-in

1) Declare the ID and version number of the plug-in

Go to the root directory build.gradle and declare the ID and version of the plug-in you want to use in Dependencies in BuildScript, as shown in the classpath

The classpath "com. Android. Tools. Build: gradle: 4.1.3." "Copy the code

Gradle then downloads the plug-in locally.

2) Application plug-ins

In the build.gradle subproject, apply the plugin through Apply and bind the plugin to the project, as shown in

apply plugin:'com.android.application'
Copy the code

The names referenced after the Apply Plugin are given in the specification by the publisher of the plug-in.

3) Plug-in parameter configuration (optional)

Some plug-ins do not need to be configured. Such as

Android {compileSdkVersion 29 buildToolsVersion "29.0.3" defaultConfig {applicationId "com.example.router" android {compileSdkVersion 29 buildToolsVersion "29.0.3" defaultConfig {applicationId "com.example.router" 29 targetSdkVersion 29 versionCode minSdkVersion 1 versionName testInstrumentationRunner "1.0" "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } }Copy the code

2.2 Usage of Script Plug-ins

Create a new file other.gradle in the root directory of your project and write the debug code as follows

Println (" I'm the code for a script plug-in ")Copy the code

Apply the script plugin to the subproject build.gradle

apply from: project.rootProject.file("other.gradle")
Copy the code

Gradle binary plug-in customization

Plug-in customization consists of three steps: creating the plug-in project, configuring parameters, publishing the plug-in, and using the plug-in.

3.1 Establish plug-in project

Complex or reusable construction logic can be implemented as binary plug-in, binary plug-in development can be in two forms, one is to implement as a common independent project, debugging needs to be manually released into Jar package to other projects reference for testing; If the logic of the plugin is written in it, Gradle will automatically package it into a binary plugin Jar at build time, which is more convenient.

1) Build a buildSrc sub-project

Build a normal project like Router, build a sub-project in the root directory buildSrc (Gradle convention must be named after this name), add build. Gradle file to the project to configure the project.

To implement this plugin using Gradle’s Groovy language, you need to rely on the Groovy plugin to compile groovy code. Declare the repository to which the third-party packages to be used belong. Specify the required third-party packages. The following code

// Reference the Groovy plugin, Var code = 'code'; var code = 'code'; var code = 'code'; var code = 'code'  implementation localGroovy() }Copy the code

2) Establish a plug-in running portal

Groovy. This class implements the Plugin interface and the apply method. When we use the Apply keyword to reference the Plugin in the project, the logic in the Apply method will be executed. You can inject plugin logic into the Apply method, such as dynamically adding a Task to a project. The code for

package com.immoc.router.gradle import org.gradle.api.Plugin import org.gradle.api.Project class RouterPlugin implements Plugin<Project> {// implement the apply method, Void apply(Project Project) {println("I am from RouterPlugin, apply from ${project.name}")}}Copy the code

Create a properties file in the meta-INFo.gradle-plugins folder and add the code

implementation-class=com.immoc.router.gradle.RouterPlugin
Copy the code

In app project build.gradle application plug-ins such as

apply plugin:'com.imooc.router'
Copy the code

3.2 Setting Parameters

The Android package configuration is called the parameter configuration and is specifically called Extension in Gradle. Enter the data we want to configure, use it in the plug-in, and finally print the APK with the corresponding properties.

There are four steps to implement the parameter configuration: Define Extension, register Extension, use Extension, and get Extension.

1) Define Extension

Create a new extension. groovy file in the Plugin directory and add the document save path parameters, such as

package com.immoc.router.gradle

class RouterExtension {
    String wikiDir
}
Copy the code

2) Sign up for Extension

Register Extension in the Apply method of a Plugin subclass, with the code shown below

package com.immoc.router.gradle import org.gradle.api.Plugin import org.gradle.api.Project class RouterPlugin implements Plugin<Project> {// implement the apply method, // Register Extension project.getextensions ().create("router", RouterExtension)}}Copy the code

3) Use Extension

In the build.gradle file that applies the plug-in, the code that uses Extension comes after the apply plug-in, such as passing an argument to wikiDir,

apply plugin:'com.imooc.router'

router {
    wikiDir getRootDir().absolutePath
}
Copy the code

4) Get Extension

Gradle life cycle: Gradle builds. Gradle builds. Gradle builds. Gradle builds.

package com.immoc.router.gradle import org.gradle.api.Plugin import org.gradle.api.Project class RouterPlugin implements Plugin<Project> {// implement the apply method, // Register Extension project.getextensions ().create("router", AfterEvaluate {RouterExtension Extension = project["router"]}}Copy the code

3.3 Publishing Plug-ins

Since the plug-in is in the form of a buildSrc subproject, it can be used directly in the current project. To be used by developers on other teams, publish the plug-in as a binary Jar package, which can be published to local or remote repositories.

To publish a plugin to a local repository, for example, we need to call the Maven plugin and configure a Task from the Maven plugin named uploadArchives, which is an Upload Task for uploading and publishing our artifacts. In buildSrc’s build.gradle file,

// Call the Maven plugin to publish the apply plugin: 'maven' // Configure the uploadArchives task uploadArchives {repositories {mavenDeployer{// set the publish path to the repo folder under the project root directory repository(url:uri('.. /repo')) {// Set groupId, usually the package name pom.groupId = 'com.imooc.router' // set artifactId, For the name of the current plug-in pom.artifactid = 'router-gradle-plugin' // Set the plug-in version pom.version = '1.0.0'}}}}Copy the code

Since it can’t be published in buildSrc, you need to copy the buildSrc directory, change the name to router-gradle-plugin, register the new project with settings.gradle, for example,

include ':app',':router-gradle-plugin'
Copy the code

Run the gradlew :router-gradle-plugin:uploadArchives command to publish the database.

3.4 Using plug-ins in the project

In the project root directory buildScript and AllProjects repositories package in the build.gradle file, configure the Maven repository address, as shown in

Maven {url uri("D: AndroidStudio \AndroidStudioProjects\ Router\ repo")} maven {url uri("D: AndroidStudio \AndroidStudioProjects\ Router\ repo")}Copy the code

Buildscript is used to get the Gradle Plugin that the script depends on, such as Android Gradle Plugin, etc. The repository in AllProjects is used to download dependencies needed by the project itself, such as Glide/OkHttp, etc.

Then tell Gradle which plug-ins from the repository you need to use, and configure them in the Dependencies package of BuildScript

GroupId: artifactId: version */ classpath 'com.imooc. Router :router-gradle-plugin:1.0.0'Copy the code

Apply the plugin to the build.gradle file of the module in which the plugin needs to be applied and pass the parameters to the plugin, as shown in

Router {wikiDir getRootDir(). AbsolutePath}Copy the code