Android Gradle plugin

Gradle plugins are classes that implement the org.gradle.api.plugin interface and have their own Plugin ID.

In Android projects, you can see the application or Libaray plugin in the build.gradle file of each module: apply plugin: ‘com.android. Application ‘, apply plugin: ‘com.android.library’

The two plug-ins to help me build apk or aar, actually respectively corresponding to the following two categories: com. Android. Build. Gradle. AppPlugin, com. Android. Build. Gradle. LibraryPlugin

Custom plug-in

Custom plug-in, mainly depends on the plug-in in the task has what function. Next, write a simple plug-in to print a line of practice, need structure directory:

  1. Create an Android project called FirstPlugin.
  2. Create the following directories and files, a total of three files.

Explanation:

1. groovy

Groovy is a groovy directory, com.xfz. Plugin is a groovy directory, and the plugin is printplugin.groovy. The code is very simple

package com.xfz.plugin

import org.gradle.api.Plugin
import org.gradle.api.Project

class PrintPlugin implements Plugin<Project> {

   void apply(Project project) {
      println("first gradle plugin ==============")}}Copy the code

2. properties

Myfirstplugin.properties file, which is the id of the plugin, is referenced as apply Plugin: ‘myFirstPlugin’ properties file by referring to the implemented plugin class:

implementation-class=com.xfz.plugin.PrintPlugin
Copy the code

3. gradle

Build. gradle consists of two parts. One is to reference Gradle plug-ins and the other is to rely on Gradle

apply plugin: 'groovy'

dependencies {
   implementation gradleApi()
   implementation 'com. Android. Tools. Build: gradle: 4.2.2'
}

repositories {
   google()
   mavenCentral()
}
Copy the code

The other part is to upload to the Maven library, using uploadArchives, where the local Maven library is simply configured

apply plugin: 'maven'

// Group and version will be used later when using custom plug-ins
group = 'com.xfz.plugin'
version = '1.0.0'

uploadArchives {
   repositories {
      mavenDeployer {
         /* repository(url: "http://www.xxx.com/repos") { authentication(userName: "admin", password: "admin") }*/

         // The default local Maven address for MAC
         repository(url: "file:///Users/xufangzhen/.m2/repository")}}}Copy the code

In settings.gradle, say include ‘:print’

Run the./gradlew uploadArchives command to upload to the repository

Maven local repository configuration

In the MAC environment:

  • First download Maven brew Install maven
  • Second, configure environment variables:
# maven export M2_HOME = / usr/local/Cellar/maven / 3.8.2 / libexec export PATH = $PATH: $M2_HOME/binCopy the code
  • Run MVN -v to check whether the command is successful

Use of custom plug-ins

For projects that need to be used, refer to build.gradle and print “First Gradle Plugin ==============” when building the project after the following three references are required.

//1. Reference the plug-in
apply plugin: 'myFirstPlugin'

buildscript {
    repositories {
        google()
        mavenCentral()
        maven {
            //2.Maven repository address
            url "file:///Users/xufangzhen/.m2/repository"}}dependencies {
        //3.groupo:module:version
        classpath 'com. XFZ. Plugin: print: 1.0.0'}}Copy the code

Develop and use plug-ins in the main project

Create a plugin project to develop a plugin. If you develop a plugin in your own project, there are several differences:

  1. Plugin modules need to be in buildSrc, no properties required, no Maven upload required in Gradle, and no include required in Settings.
  2. Reference plug-in makes a direct reference to the plug-in class without quotes
apply plugin: com.xfz.plugin.PrintPlugin
Copy the code

Upload the AAR plug-in

In our component-development, we will have modules that will be packaged as AArs and uploaded to the Maven library, so we can package the uploaded task as a plug-in without having to configure uploadArchives everywhere

With that in mind, let’s take a look at the overall project structure: one plug-in and one task

AarUploadTask inherits from the upload

The code is as follows: the groupId, artifactId, and version variables are used to configure the version of the AAR’s name. If the version is not snapshot, the AAR is named tag

package com.xfz.plugin.upload

import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.Upload

class AarUploadTask extends Upload {
   String groupId = null
   String artifactId = null
   String version = null

   @TaskAction
   protected void upload() {
      if (groupId == null || artifactId == null) {
         return
      }
      // Configure the repository. This demo sets up local Maven libraries
      repositories {
         mavenDeployer {
            repository url: "file:///Users/xufangzhen/.m2/repository"
            // Calculate the version information, if it is snapshot version, take the version number directly, if it is official version, take the last tag as the version number
            pom.version = getVersionName()
            pom.artifactId = artifactId
            pom.groupId = groupId
         }
      }
      // Start uploading
      println "start upload " + groupId + ":" + artifactId + ":" + version
      super.upload()
   }

   /** * ./gradlew clean -PisSnapshot=false :base:aarUpload **/
   def getVersionName() {
      def isSnapshot = ""
      if (project.hasProperty("isSnapshot")) {
         isSnapshot = project.property("isSnapshot")}// If it is snapshot and the version number is not empty, use the version number -snapshot
      if(Boolean.parseBoolean(isSnapshot) && version ! =null) {
         return version + '-SNAPSHOT'
      } else if(version ! =null && version.length() > 0) {
         return version
      } else {
         // Otherwise use the last submitted tag name
         return 'git describe --tags --abbrev=0'.execute().text.trim()
      }
   }
}
Copy the code

AarUploadPlugin implements Plugin

package com.xfz.plugin.upload

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.tasks.bundling.Jar

class AarUploadPlugin implements Plugin<Project> {
   void apply(Project target) {
      target.pluginManager.apply 'maven'
      def aarUploadTask = target.task('aarUpload'.type: AarUploadTask, dependsOn: 'assemble')
      // Set the source code upload
      aarUploadTask.doFirst {
         target.task(type: Jar) {
            classifier = 'sources'
            from android.sourceSets.main.java.srcDirs
         }
      }
      aarUploadTask.configuration = target.configurations.archives
   }
}
Copy the code

use

apply plugin: 'aar.upload'

aarUpload {
    artifactId = 'base' / / aar name
    version = '1.3.0' / / version
    groupId = 'com.xfz.plugin' //groupId
}

// Set the classpath in the outermost layer of build.gradle
Copy the code