在Android项目中自定义Gradle插件

编写groovy插件

在使用build.gradle编译项目时,需要使用

apply plugin: "xxxxx"

告诉build.gradle接下来要编译的是什么项目类型,不同的项目类型规定有不同的文件目录,所以在创建项目时,一旦项目类型确定,该项目的文件目录结构也是确定的。
当指定的文件类型为gradle插件时,其文件目录树为:
在这里插入图片描述

  1. 建立模块根目录:在项目根目录下添加script文件夹
  2. 为插件模块添加build.gradle: 在script目录下建立build.gradle文件,并指定将要编译的项目为groovy插件
//: build.gradle
apply plugin: "groovy"
dependencies {
  implementation gradleApi()
   implementation localGroovy()
}

3.构建模块内容目录:在script目录下建立src/main文件夹,并在src/main文件目录下创建groovyresources文件夹,并在groovyresources文件夹中添加如上图的子文件

a) 其中MyPlugin.groovy为插件的groovy文件,代码如下:

package com.example.script
import org.gradle.api.Plugin
import org.gradle.api.Project
class MyPlugin implements Plugin<Project> {
   @Override
   void apply(Project project) {
	//定义任务名称为testPlugin
       project.task("testPlugin", {
           println("hello gradle plugin is src")
       })
   }
}

b) 注意META-INF/gradle-plugins下建立的properties文件的文件名就是插件的名称

  1. 在配置文件中注册插件类:
implementation-class=com.example.script.MyPlugin

将插件上传至本地Maven仓库

在插件模块根目录的build.gradle文件中添加将插件上传至本地maven,最终的build.gradle文件为

apply plugin: "groovy"

dependencies {
    implementation gradleApi()
    implementation localGroovy()
}

apply plugin: 'maven'
group = 'com.github.xxxxx'
version = '1.0.0'

uploadArchives {
    repositories {
        mavenDeployer {
            //本地的Maven地址设置为../repos
            repository(url: uri('../repo'))
        }
    }
}

然后,在gradle的任务栏中执行插件上传本地maven仓库的Task

在项目中使用插件

在项目的build.gradle中添加插件的本地maven地址和classpath

buildscript {
    repositories {
        google()
        jcenter()
        maven {
            url uri('./repo')
        }
    }
    dependencies {
        classpath 'com.github.jiarwang:script:1.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

在需要使用的模块的build.gradle中使用插件,插件名称应与插件配置文件.properties的文件名一致

apply plugin : 'com.plugin.gradle'

最后在Task中执行相关任务。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值