上一篇介绍了 Gradle的一些核心知识点,构建生命周期,Project以及Task等,本篇主要介绍如何开发一个Gradle插件
1、Gradle插件介绍 我们在日常开发中经常看到
1 apply plugin: 'com.android.application'
这其实就是引用了一个官方的插件。插件的本质实际上就是把独立的逻辑抽取封装,以便于更加高效的复用,主要分为以下2大类
即实现了 org.gradle.api.plugins 接口的插件,然后被工程引用(apply),有以下3种编写形式
build.gradle文件中直接编写
buildSrc默认插件目录下编写
在自定义项目中编写 其中第三种编写方式复用性最高
下面将详细介绍下各个方式
2、脚本插件 这个比较简单,创建一个插件xx.gradle,然后在其他的 build.gradle中通过 apply from 引用即可
3、对象插件 3.1、build.gradle 文件中直接编写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 apply plugin: Method1Plugin class Method1Plugin implements Plugin <Project > { @Override void apply(Project project) { println '自定义 Method1Plugin ' project.task("Method1PluginTask" ){ doLast { println 'Method1PluginTask exec success...' } } } } ./gradlew Method1PluginTask > Configure project : app I am Method1Plugin > Task : app: Method1PluginTask Method1PluginTask exec success...
这种方式有这很大的局限性,只能在当前脚本中使用,不符合复用原则
3.2、buildSrc文件夹中编写 buildSrc是Gradle默认的插件目录,跟Debug目录类似有这特殊作用,该目录下的代码会在构建时被编译打包,然后会被添加到buildScript中的classpath下,可以在项目中别的build.gradle中使用
Tips: buildSrc的执行时机不仅早于任何一个project(build.gradle)而且也早于settings.gradle
不能在settings.gradle中添加
创建一个名为 buildSrc 的Java Module
修改build.groovy文件中的内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 apply plugin: 'groovy' dependencies { implementation gradleApi() implementation localGroovy() } repositories { mavenCentral() } sourceSets { main { groovy { srcDir 'src/main/groovy' } resources { srcDir 'src/main/resources' } } }
这样 gradle就能把它识别成一个插件目录
编写插件 实现 Plugin接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class CustomGradlePlugin implements Plugin <Project > { @Override void apply(Project project) { println "Hello plugin..." + project.name } }
插件注册
方式1
在 src/main 下创建 resources 目录,在 resources 目录下创建 META-INF 目录,在 META-INF 目录下创建 gradle-plugins 目录,在 gradle-plugins 目录下创建 .properties 为后缀的文件,名字可以根据自己的喜好取,最后在创建的 properties 文件下标识该插件对应的类路径即可完成插件的注册
1 implementation-class =com .dream .plugin .BuildSrcPlugin
Tips 类名都是固定的,写错会引用不到 META-INF这个里面的文件名称很重要,后续通过apply引用就是这个名字,比如这里的文件为BuildSrcPlugin.properties,那么引用插件使用 1 apply plugin: 'BuildSrcPlugin'
方式2
直接在插件的build.gradle中进行如下配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 apply plugin: 'java-gradle-plugin' gradlePlugin { plugins { greeting { id = 'BuildSrcPlugin' implementationClass = 'com.dream.plugin.BuildSrcPlugin' } } }
通过以上4步就可以使用插件
这种方式也有缺点,只能在当前的项目工程下使用
3.3、自定义目录中编写 上面的2种方式都只能在当前工程使用,自定义项目中则没有这个限制,可以编写完插件 然后发布到远程仓库核心操作跟在buildSrc文件中编写一致 ,只是在新建文件夹中增加了上传到远程仓库的配置
下如图所示,增加一个自定义插件的JavaModule
上传仓库部分在gradle中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 apply plugin: 'groovy' apply plugin: 'java-gradle-plugin' apply plugin: 'maven' dependencies { implementation gradleApi() implementation localGroovy() } repositories { mavenCentral() } gradlePlugin { plugins { greeting { id = 'CustomPlugin' implementationClass = 'com.dream.plugin.CustomPlugin' } } } uploadArchives { repositories { mavenDeployer { pom.groupId = 'com.dream' pom.artifactId = 'customplugin' pom.version = '1.0.0' repository(url: uri('../customplugin' )) } } }
上面的插件增加2块内容
采用了Gradle配置的方式进行插件注册
上传到本地maven仓库的配置
最后还要发布插件到mavean仓库
1、执行 ./gradlew uploadArchives 命令
2、在 AndroidStudio 找到 Gradle 可视化界面的 uploadArchives Task 点击发布
4、插件调试 日志调试 日志调试也是 可以通过一个单例接收logger
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 object PluginUtil { lateinit var logger: Logger } open class ClaymorePlugin : Plugin <Project > { override fun apply (project: Project ) { if (project.plugins.find { it is AppPlugin } == null ) { return } ClaymoreForge.logger = project.logger } PluginUtil.logger.lifecycle("全量transform cost ${(System.currentTimeMillis() - startTimeFull)} " )
clean project然后 make 一下工程日志就能出现了。
断点调试
首先需要添加一个Remote配置
选择 Remote调试
取名创建Remote类型的配置
选择创建的配置,执行调试命令
./gradlew assembleDebug -Dorg.gradle.debug=true –no-daemon
此时我们的命令会进入一个锁定状态,等待我们进行下一步操作
断点 调试
5、插件数据 Extension 在开发插件中,经常需要配合数据,Extension跟Java Bean类似, 比如我们经常看到的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 android { compileSdkVersion 26 defaultConfig { applicationId "com.hm.iou.thinapk.demo" minSdkVersion 19 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt' ), 'proguard-rules.pro' } } }
一般我们通过ExtensionContainer来创建和管理Extension,如同TaskContainer创建和管理Task一样,通过Project中的
1 2 ExtensionContainer getExtensions()
5.1、 一个例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Foo { int age String username String toString() { return "name = ${username}, age = ${age}" } } getExtensions().create("foo" , Foo) foo { age = 30 username = "xsf" } task testExt << { println project.foo }
核心API
1 2 3 <T> T create(String name, Class<T> type, Object... constructionArguments) <T> T create(Class<T> publicType, String name, Class<? extends T> instanceType, Object... constructionArguments)
API 所有参数的含义。
publicType:创建的 Extension 实例暴露出来的类类型;
name:要创建的Extension的名字,可以是任意符合命名规则的字符串,不能与已有的重复,否则会抛异常;
instanceType:该Extension的类类型;
constructionArguments:类的构造函数参数值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 class Animal { String username int legs Animal(String name) { username = name } void setLegs(int c) { legs = c } String toString() { return "This animal is $username, it has ${legs} legs." } } class Pig extends Animal { int age String owner Pig(int age, String owner) { super ("Pig" ) this .age = age this .owner = owner } String toString() { return super .toString() + " Its age is $age, its owner is $owner." } } Animal aAnimal = getExtensions().create(Animal, "animal" , Pig, 3 , "alen" ) Pig aPig = getExtensions().create("pig" , Pig, 5 , "kobe" ) animal { legs = 4 } pig { setLegs 2 } task testExt << { println aAnimal println aPig println "aPig is a instance of ExtensionAware : ${aPig instanceof ExtensionAware}" }
运行打印如下
1 2 3 This animal is Pig, it has 4 legs. Its age is 3 , its owner is alen. This animal is Pig, it has 2 legs. Its age is 5 , its owner is kobe. aPig is a instance of ExtensionAware : true
官方文档里还说明了一个特性,创建的 Extension 对象都默认实现了 ExtensionAware 接口
5.2、嵌套Extension 比如这个例子
1 2 3 4 5 6 7 8 9 10 11 outer { outerName "outer" msg "this is a outer message." inner { innerName "inner" msg "This is a inner message." } }
这种嵌套的该如何处理呢,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 class OuterExt { String outerName String msg InnerExt innerExt = new InnerExt() void outerName(String name) { outerName = name } void msg(String msg) { this .msg = msg } void inner(Action<InnerExt> action) { action.execute(inner) } void inner(Closure c) { org.gradle.util.ConfigureUtil.configure(c, innerExt) } String toString() { return "OuterExt[ name = ${outerName}, msg = ${msg}] " + innerExt } } class InnerExt { String innerName String msg void innerName(String name) { innerName = name } void msg(String msg) { this .msg = msg } String toString() { return "InnerExt[ name = ${innerName}, msg = ${msg}]" } } def outExt = getExtensions().create("outer" , OuterExt)outer { outerName "outer" msg "this is a outer message." inner { innerName "inner" msg "This is a inner message." } } task testExt << { println outExt }
关键在下面2个函数
1 2 void inner(Action<InnerExt> action)void inner(Closure c)
定义在 outer 内部的 inner ,Gradle 解析时实质上会进行方法调用,也就是会执行 outer.inner(…) 方法,而该方法的参数是一个闭包,因此在类 OuterExt 中需要定义 inner(…) 方法
打印结果如下
1 OuterExt[ name = outer, msg = this is a outer message.] InnerExt[ name = inner, msg = This is a inner message.]
5.3、NamedDomainObjectContainer 上面介绍的都是固定项配置的,要是不定项配置比如类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 android { buildTypes { release { minifyEnabled true zipAlignEnabled true shrinkResources true proguardFiles getDefaultProguardFile('proguard-android.txt' ), 'proguard-rules.pro' signingConfig signingConfigs.hmiou } debug { signingConfig signingConfigs.hmiou } } }
不光支持release、debug,还可以随意命名配置,这时候就需要NamedDomainObjectContainer (命名领域对象容器)
核心API
1 2 3 <T> NamedDomainObjectContainer<T> container(Class<T> type) <T> NamedDomainObjectContainer<T> container(Class<T> type, NamedDomainObjectFactory<T> factory) <T> NamedDomainObjectContainer<T> container(java.lang.Class<T> type, Closure factoryClosure
来看个case
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 class TestDomainObj { String name String msg public TestDomainObj(String name) { this .name = name } void msg(String msg) { this .msg = msg } String toString() { return "name = ${name}, msg = ${msg}" } } class TestExtension { NamedDomainObjectContainer<TestDomainObj> testDomains public TestExtension(Project project) { NamedDomainObjectContainer<TestDomainObj> domainObjs = project.container(TestDomainObj) testDomains = domainObjs } void testDomain(Action<NamedDomainObjectContainer<TestDomainObj>> action) { action.execute(testDomains) } void test() { testDomains.all { data -> println data } } } def testExt = getExtensions().create("test" , TestExtension, project)test { testDomain { domain2 { msg "This is domain2" } domain1 { msg "This is domain1" } domain3 { msg "This is domain3" } } } task myTask << { testExt.test() }
运行结果如下
1 2 3 name = domain1, msg = This is domain1 name = domain2, msg = This is domain2 name = domain3, msg = This is domain3
总结 本文主要介绍了自定义插件的几种方式以及优缺点,以及如何通过远程调试插件,并且顺带介绍了插件中数据Extension的用法
参考
深度探索 Gradle 自动化构建技术(四、自定义 Gradle 插件)
Gradle 系列 (三)、Gradle 插件开发
Android Gradle学习(六):NamedDomainObjectContainer详解
深入理解Gradle框架之一:Plugin, Extension, buildSrc