Android Gradle plug-in development for the first time

table of Contents

One, Android Gradle plugin

Two, Android Gradle plug-in classification

Three, custom Gradle plugin

1. Create Gradle Module

2. Configure Gradle development environment

3. Add the relevant code for custom Gradle

4. Plug-in release

5. Use plug-ins

Four, summary


One, Android Gradle plugin

Developers who are familiar with using Android Studio to build Android projects know that when we create an Android project, we will generate a build.gradle file in the root directory of the project and the root directory of each Module, and build.gradle in the Module directory. The file will have the following description:

plugins {
    id 'com.android.application'
}

or

apply plugin: 'com.android.application'

Then this com.android.application is the Android Gradle plugin.

The Android Gradle plug-in is used to build Android projects. The plug-in is developed by the Google team. In this way, some libraries are provided for developers to call. The advantage of using this kind of Gradle plug-in is that it can realize the reuse of code and resources through simple configuration, and it is more convenient to create derivative versions of applications, such as multi-channel packaging.

Two, Android Gradle plug-in classification

There are mainly three kinds of engineering projects built by Android Studio: the first is the Application project, which can be run to generate a runnable APK; the second is the Library project, which can generate aar for other Application projects; third This kind of project is Test project, which is mainly used for Application project and Library project test.

Then these three projects correspond to the three Android Gradle plug-ins, which is the first relevant content in the build.gradle files of the Module and Library projects in the project:

  • (1) What is set in build.gradle in the Module project is
apply plugin: 'com.android.application'
  • (2) What is set in build.gradle in the Library project is
apply plugin: 'com.android.library'
  • (3) What is set in build.gradle in the Test project is
apply plugin: 'com.android.test'

'com.android.application','com.android.library', and'com.android.test' are the unique id identifiers of these Android Gradle plugins. Add the corresponding Android Gradle plugin to the corresponding project, then finally compile the entire project It will be packaged together according to different functions.

We add an Android Gradle plug-in to the project actually includes two parts: one is the aforementioned application Android Gradle plug-in, and the other is to specify the execution environment of the plug-in before the application. These Android Gradle plugins provided by Google are hosted on jcenter, so it is usually necessary to configure the execution environment of these plugins in the build.gradle of the root directory of the project, as follows:

buildscript {
    repositories {
//配置插件的仓库
        google()
        jcenter()
    }
    dependencies {
//配置插件的依赖
        classpath "com.android.tools.build:gradle:4.1.1"
    }
}

In the first part, it is also mentioned that the Gradle plugin is used. You can reuse code and resources by simply configuring and running some parameters. Then, like these Android Gradle plugins provided by Google, the configuration entry is provided through android{}, which is The basic content of some Android projects that we usually add to the build.gradle file of the Module:

android {
    compileSdkVersion 30

    defaultConfig {
        applicationId "com.android.androidplugin"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Three, custom Gradle plugin

Through the Android Gradle plug-in provided by Google analyzed above, it is understood that a Gradle plug-in includes: a unique id identifier, an execution environment (including maven warehouse and dependencies), a configuration item, and functions that the plug-in needs to implement . Then we should also include these four parts when customizing a Gradle plugin. Now let's explain how to create a simple Gradle plug-in from these four aspects.

1. Create Gradle Module

 Android Studio has not yet provided a similar Gradle Plugin shortcut, so we need to create this Gradle plugin by ourselves.

  • (1) Create a new Android Project

It is the way we usually create a new Android Project to create the project, named AndroidPlugin

  • (2) Create a new Module

Here is also the usual way to create a Module to create a Module. The type of Module that can be used here can be any type, which can be Phone&Tablet Module or Android Library, because the module is created only as a container for plug-ins, and most of the content in it needs to be deleted.

Name the Module as FirstPlugin, then remove the files inside build.gradle and the src/main directory, delete all the rest, leave only the directory in the src/main directory, and delete all the files inside.

  • (3) Add related file directories

1) Since Gradle is based on groovy, the development of a Gradle plug-in is equivalent to a groovy project, so a groovy directory should be created under src/main

2) The groovy project is based on java, so the way to add files later is similar to the java project. We can manage java files in a package way. Here we create a directory named com.wj.plugin

3) Create a configuration file with the repository and name under src/main, that is, create a com.wj.firstplugin.properties file under resources/META-INF/gradle-plugins. Note that this com.wj.firstplugin is the custom plug-in Name, which is the unique id

2. Configure Gradle development environment

Add the following content to the build.gradle file in the root directory of FirstPlugin:

apply plugin: 'groovy'
apply plugin: 'maven'


dependencies {
    //gradle sdk
    implementation gradleApi()
    //groovy sdk
    implementation localGroovy()
}

repositories {
    mavenCentral()
}

//打包到本地或者远程maven库
uploadArchives {
    repositories {
        mavenDeployer {
            //这个就是配置这个自定义插件的classpath
            pom.groupId = 'com.wj.plugin'
            pom.artifactId = 'FirstPlugin'
            pom.version = '1.0.0'
            //提交到远程服务器
            // repository(url:"服务器地址"){
            //    authentication(userName:'admin',password:'admin')
            // }
            //本地maven地址
            repository(url: uri('../plugins'))
        }
    }
}

Simply note the groupId, artifactId, version:

(1) groupId: define which group the project belongs to

(2) artifaceId: Define the unique Id of the current maven project in the group

(3) version: current version number

Finally, these three values ​​are used to specify the classpath of the Gradle as'groupId:artifaceId:version', which is the classpath we rely on when using the plug-in: com.wj.plugin:FirstPlugin:1.0.0 .

3. Add the relevant code for custom Gradle

  • (1) Create the plug-in entry file FirstPlugin.java under src/main/groovy/com/wj/plugin, and this class should implement Plugin<Project>, the code is as follows:
public class FirstPlugin implements Plugin<Project> {

    @Override
    public void apply(Project project) {
        System.out.println("================");
        System.out.println("Hello FirstPlugin");
        System.out.println("================");
    }
}
  • (2) Under the resources/META-INF/gradle-plugins/com.wj.firstplugin.properties file, configure the plug-in entry class, the code is as follows:
#配置插件的入口类
implementation-class=com.wj.plugin.FirstPlugin
  • (3) Click on the Gradle tool on the right side of Android Studio

Click build in Tasks, there is no compilation exception

Executing tasks: [build] in project /Users/j1/Documents/android/code/studio/AndroidPlugin/FirstPlugin

> Task :FirstPlugin:compileJava NO-SOURCE
> Task :FirstPlugin:compileGroovy UP-TO-DATE
> Task :FirstPlugin:processResources UP-TO-DATE
> Task :FirstPlugin:classes UP-TO-DATE
> Task :FirstPlugin:jar UP-TO-DATE
> Task :FirstPlugin:assemble UP-TO-DATE
> Task :FirstPlugin:compileTestJava NO-SOURCE
> Task :FirstPlugin:compileTestGroovy NO-SOURCE
> Task :FirstPlugin:processTestResources NO-SOURCE
> Task :FirstPlugin:testClasses UP-TO-DATE
> Task :FirstPlugin:test NO-SOURCE
> Task :FirstPlugin:check UP-TO-DATE
> Task :FirstPlugin:build UP-TO-DATE

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 208ms
3 actionable tasks: 3 up-to-date
16:14:46: Task execution finished 'build'.

Click the jar in Tasks to generate FirstPlugin.jar under build/libs.

4. Plug-in release

After the above three steps, a simple custom Gradle plugin is complete. Then it has to be packaged and released. This is the content of uploadArchives{} in the configuration build.gradle mentioned in the second step. If it is uploaded to a remote server, configure the following:

     //提交到远程服务器
     repository(url:"服务器地址"){
         authentication(userName:'admin',password:'admin')
      }

If it is only localized, the following method can be used directly 

      //本地maven地址
      repository(url: uri('../plugins'))

The above two Ge url this is what we use custom plugins in the back warehouse 

After the configuration is complete, click the uploadArchives of upload under Tasks of the gradle tool on the right to complete the packaging and publishing.

After completion, a file with the following structure will be generated in the root directory of the project

So far, a process of customizing the Gradle plugin has been completed. The unique ID of the Gradle plug-in is com.wj.firstplugin, which is the file name of the com.wj.firstplugin.properties file created under resources/META-INF/gradle-plugins; the maven repository needed to configure the environment is /plugins and The dependent classpath is com.wj.plugin:FirstPlugin:1.0.0

5. Use plug-ins

The use of the plug-in can be completed by configuring the Module of our Android app and build.gradle in the root directory of the project.

  • (1) Configure the maven warehouse and dependent classpath in build.gradle of the project's root directory
buildscript {
    repositories {
         。。。。。。
        //FirstPlugin的maven仓库
        maven{
        //maven仓库的地址
           url uri('plugins')
        }
    }
    dependencies {
         。。。。。。。。。
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        //FirstPlugin的依赖
        classpath "com.wj.plugin:FirstPlugin:1.0.0"
    }
}
  • (2) Use the plug-in in build.gradle under the app module
plugins {
     //该插件的id
    id 'com.wj.firstplugin'
}
  • (3) Compile the project, you will see the previous log output

Four, summary

Now I have a little feeling and knowledge about the development of Gradle plugin for Android. In this article, I mainly introduce "a unique ID" and "an execution environment (including maven warehouse and dependencies)" of a custom Gradle plugin. As for "a configuration item", it will be summarized separately or added later.

Learning is happy, come on! ! ! !

The relevant code has been uploaded to github. github address: https://github.com/wenjing-bonnie/AndroidPlugin.git

Guess you like

Origin blog.csdn.net/nihaomabmt/article/details/112308851