Gradle插件使用过程记录

Android中基于Gradle进行编译打包的过程,下面记录一下如何进行Gradle插件开发的过程:html

首先在项目中新建的一个名为buildSrc的module,为何叫这个名字请看官方文档。而后将Java文件夹以及res文件夹删除,新建groovy文件夹以及resource文件夹:java

在groovy文件夹下新建package的目录,在我这依次是com/lin/plugin,而后在resource文件夹下创建META-INF/gradle-plugins两个文件夹,在文件夹中添加包名.properties文件,其内部代码以下:android

implementation-class=com.lin.plugin.TestPlugin

TestPlugin.groovy的代码以下:app

class TestPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        println('--------------------------')
        println('this is a buildSrc plugin...')
        println('--------------------------')
    }
}

修改buildSrc的build.gradle文件:maven

//添加groovy和maven插件
apply plugin: 'groovy'
apply plugin: 'maven'

//本地发布插件
uploadArchives {
    repositories {
        mavenDeployer {//用于发布本地maven
            pom.groupId = "com.lin.plugin"
            pom.artifactId = "test"
            pom.version = "0.0.1"
            repository(url: uri('../repo'))
        }
    }
}
task sourcesJar(type: Jar) {
    from project.sourceSets.main.groovy.srcDirs
    classifier = 'sources'
}
task javadocJar(type: Jar, dependsOn: groovydoc) {
    classifier = 'javadoc'
    from groovydoc.destinationDir
}
artifacts {
    archives javadocJar
    archives sourcesJar
}
//插件依赖
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile gradleApi()
    compile localGroovy()
}

而后在项目根目录的build.gradle中添加本地maven库,目的是为了可以在主工程中使用咱们建立的插件:ide

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
        maven{
            url uri('./repo')//本地maven,用于发布测试插件
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath 'com.lin.plugin:test:0.0.1'//本地maven,依照上面uploadArchives内的命名组装
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

进行编译,编译完成后在插件的gradle命令中能够看到多出了以下命令:测试

双击该命令用于构建插件库,构建完成后可以在项目根目录下看见生成问maven文件:gradle

而后将插件导入咱们的主工程build.gradle当中ui

apply plugin: 'com.lin.plugin'

运行assemble命令,构建项目,能够run窗口看到TestPlugin的执行:this

经过该方式就编译好了一个Plugin插件了,若是项目须要针对apk的编译打包流程作一些处理的话,就能够使用上述的插件进行hook的操做了,关于更多的gradle使用方法,移步官网阅读便可。

相关文章
相关标签/搜索