Gradle插件开发:基础篇

运行环境

  • Android Studio 3.0.1
  • classpath ‘com.android.tools.build:gradle:3.0.1’

准备开始

  1. 通过New Module,新建一个Java Library或者Android Library项目,名称为plugin
  2. 重命名java目录为groovy目录
  3. 新建resources(与groovy同级)/META-INF/gradle-plugins/com.test.properties
  4. 编辑properties内容为implementation-class=com.xxx.plugin.TestPlugin

    具体实现

    配置plugin项目的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
    32
    33
    apply plugin: 'java'
    apply plugin: 'maven'
    apply plugin: 'groovy'

    compileGroovy {
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
    options.encoding = "UTF-8"
    }

    repositories {
    google()
    jcenter()
    mavenCentral()
    }

    dependencies {
    compile gradleApi()
    compile localGroovy()
    compile 'com.android.tools.build:gradle:3.0.1'
    }
    //发布到本地maven仓库
    group = 'com.xxx.plugin'
    version = '1.0.1'

    uploadArchives {
    version = version + '-SNAPSHOT'
    repositories {
    mavenDeployer {
    snapshotRepository(url: uri('../repo'))
    }
    }
    }

新建TestPlugin实现Plugin接口

1
2
3
4
5
6
7
8
9
10
11
12
class TestPlugin implements Plugin<Project>{

@Override
void apply(Project project) {
project.task('helloPluginTask') {
group 'junli'
doLast {
println 'hell i am a task in plugin'
}
}
}
}

上传到本地Maven库

执行uploadArchives把plugin上传到本地maven仓库

使用Gradle Plugin

项目根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
32
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

repositories {
google()
jcenter()
//添加maven引用
maven {
url uri('./repo')
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
//添加plugin引用
classpath 'com.xxx.plugin:plugin:1.0.1-SNAPSHOT'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

应用build.gradle 配置如下

1
apply plugin: 'com.test'

执行插件

1
./gradlew helloPluginTask

您的支持是我原创的动力