0%

Android项目构建Gradle专栏——gradle plugin

公众号地址: https://mp.weixin.qq.com/s/P9DgxZ22kwIXCl_M5urxCg


1. gradle build生命周期

gradle是Android用来build的工具, 而gradle plugin是封装好的可以复用的gradle script

gradle build的声明周期如下:

  • Initialization
  • Configuration
  • Execution

在项目中使用的gradle plugin:
build.gradle文件中

1
2
3
4
5
plugins {
id 'java-gradle-plugin'
id 'maven-publish'
id 'ivy-publish'
}

声明使用的gradle插件在configuration阶段会进行解析,提取里面的task构造有向无环图
然后在 execution 阶段依次根据图执行 task 完成 build

2. 开发 gradle 插件

首先开发一个 gradle plugin,有以下方法:

  • Build script: build.gradle 中写
  • buildSrc project:rootProjectDir/buildSrc/src/main/java下写
  • Standalone project:插件独立 project 开发后打成jar包,其他项目依赖jar包使用plugin
    可以参考官方 gradle 开发手册中:

    最简单的方法开发一个插件: build.gradle 中进行开发
    最常用的方法开发插件: 独立project中开发,这样其他 project 通过依赖jar包,可以轻松引入使用

3. build.gradle 开发 gradle plugin

在项目 build.gradle 中直接声明和使用 自定义 gradle plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
project.task('hello') {
doLast {
println 'Hello from the GreetingPlugin'
}
}
}
}

// Apply the plugin
apply plugin: GreetingPlugin

运行这个 task

1
gradle -q hello

这样就可以运行这个自定义的 task

增加定义 extension 然后在 build.gradle 中配置,在 plugin 中读取配置运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interface GreetingPluginExtension {
Property<String> getMessage()
Property<String> getGreeter()
}

class GreetingPlugin implements Plugin<Project> {
void apply(Project project) {
def extension = project.extensions.create('greeting', GreetingPluginExtension)
project.task('hello') {
doLast {
println "${extension.message.get()} from ${extension.greeter.get()}"
}
}
}
}

apply plugin: GreetingPlugin

// Configure the extension using a DSL block
greeting {
message = 'Hi'
greeter = 'Gradle'
}

4. 独立项目 开发 gradle plugin

独立项目中开发的 gradle plugin提供给其他的 project 使用需要打出 jar 包
然后使用 classpath 来依赖 jar 包,即可在 使用的 build.gradle 中使用该 plugin

开发和上传 gradle plugin

  1. 新建一个 module
  2. build.gradle 文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
plugins {
id 'groovy'
id 'java-library'
id 'maven'
}

dependencies {
implementation gradleApi()
implementation 'com.android.tools.build:gradle:4.1.3'
}

uploadArchives {
repositories {
mavenDeployer {
pom.groupId = 'com.gongshijie.greet'
pom.version = '1.0'
pom.artifactId = 'greet'
// repo仓库路径,可以使用相对路径
repository(url: uri('../../repo'))
}
}
}
  1. 插件内容代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    class GreetingPlugin implements Plugin<Project> {
    void apply(Project project) {
    project.task('hello') {
    doLast {
    println 'Hello from the GreetingPlugin'
    }
    }
    }
    }
  2. 插件资源描述:

    1
    implementation-class=com.gongshijie.plugin.GreetingPlugin

    目录结构

  3. 插件的使用
    在需要使用插件的 module build.gradle 中

    也可以单独在 gradle侧边栏 other 下看到该插件中的task

以上就完成了一个插件开发的过程

实际上 可以使用 Bytex 来进行插件开发,然后使用 Jitpack 来进行插件的发布,后面我们会介绍如何使用ByteX开发插件,如何发布插件到 Jitpack 供其他项目通过classpath 形式引入

微信扫码关注公众号,追踪更多博文