Gradle plugin自定义

背景

最近组里gradle大神带大家一起飞,lz也趁机学习一下Gradle相关的知识。我们工程中的gradle的脚本几乎是我所见过的最复杂的工程(另一个是Tinker),里面有自定义的plugin,也有自己执行的一些脚本,如lint,时间监听,findbugs,Checkstyle等,也使用gradle transform api 动态插桩。lz 作为小白,默默从自定义gradle plugin 开始。

先看gradle的工程结构图

Paste_Image.png

主工程app, submodule helloplugin

helloplugin 通过新建

Paste_Image.png
Paste_Image.png

lets go

helloplugin 的gradle配置如下

apply plugin: 'groovy'
//添加maven plugin, 用于发布我们的jar
apply plugin: 'maven'


dependencies {
    compile gradleApi()
    compile localGroovy()
}

repositories {
    mavenCentral()
}


//设置maven deployer
uploadArchives {
    repositories {
        mavenDeployer {
            //设置插件的GAV参数
            pom.groupId = 'plugin'
            pom.artifactId = 'helloplugin'
            pom.version = 1.2
            //文件发布到下面目录
            repository(url: uri('../release'))
        }
    }
}

其中uploadArchives用于上传plugin到本地release文件夹下(实际使用一般 是私有maven仓库)。 其实看过我前面IntelliJ IDEA spring mvc +mybatis 环境搭建服务器 http://www.jianshu.com/p/c7060f84bf5c 等系列的童鞋不会陌生groupId、artifactId、version 目的是相当于配置一个工程唯一id。

新建groovy和resources文件夹

Paste_Image.png

主插件类HelloPlugin.groovy

package plugin

import org.gradle.api.Plugin
import org.gradle.api.Project

public class HelloPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {

        project.extensions.create('apkdistconf', ApkDistExtension);
        project.task('hellotask') << {
            println "hello, this is test task!"
        }
        project.afterEvaluate {

            //只可以在 android application 或者 android lib 项目中使用
            if (!project.android) {
                throw new IllegalStateException('Must apply \'com.android.application\' or \'com.android.library\' first!')
            }

            //配置不能为空
            if (project.apkdistconf.nameMap == null || project.apkdistconf.destDir == null) {
                project.logger.info('Apkdist conf should be set!')
                return
            }

            Closure nameMap = project['apkdistconf'].nameMap
            String destDir = project['apkdistconf'].destDir

            //枚举每一个 build variant,生成的apk放入如下路径和文件名
            project.android.applicationVariants.all { variant ->
                variant.outputs.each { output ->

                    File file = output.outputFile
                    print("dir " + destDir + " " + file.getName())
                    output.outputFile = new File(destDir, nameMap(file.getName()))
                }
            }
        }

    }

}

需要继承 Plugin<Project> ,当主gradle使用//使用helloplugin
apply plugin: 'helloplugin'时,就会调用apply方法。

ApkDistExtension.groovy扩展的属性

package plugin

class ApkDistExtension {
    Closure nameMap = null;
    String destDir = null;
}

groovy语法,默认生成get和set方法。

配置指向插件的主类HelloPlugin

Paste_Image.png
implementation-class=plugin.HelloPlugin

注意路径为plugin.HelloPlugin 全包名 + 类名

编译

此时会发现

Paste_Image.png

运行uploadArchives task就可以将其打包到本地了。
此时,如下:

Paste_Image.png

使用

Paste_Image.png
import plugin.HelloWorldTask

apply plugin: 'com.android.application'
//使用helloplugin
apply plugin: 'helloplugin'


buildscript {
    repositories {
        maven {
            //cooker-plugin 所在的仓库
            //这里是发布在本地文件夹了
            url uri('../release')
        }
    }
    dependencies {
        //引入helloplugin
        classpath 'plugin:helloplugin:1.2'
    }

    tasks.withType(JavaCompile) {
        sourceCompatibility = JavaVersion.VERSION_1_7
        targetCompatibility = JavaVersion.VERSION_1_7
    }
}

task hello1(type:HelloWorldTask){
    message ="I am a programmer"
}


apkdistconf {
    nameMap { name ->
        println 'hdasd, ' + name
        return name
    }
    destDir "$project.path"
}



android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.nothing.plugindemo"
        minSdkVersion 11
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}



dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile project(':helloplugin')
}

type:HelloWorldTask是helloplugin里面自定义的一个task不影响使用,可以去掉或参考我上传的。
正常运行即可。
这里有几点说明下,其他groovy还是和其他脚本很相似的,闭包也与lamda表达式类似。 destDir "$project.path"相当于 setDestDir("$project.path"), $用户变量,与其他脚本类似。

遇到的问题

第一个问题,找不到,这里需要分析找不到ext的原因: 本来未定义或其他,这里是我自己已经upload了一次之后,没有upload新的gradle plugin,自己挖的坑含着泪也要跳下去。

Error:(25, 0) Could not find method sa() for arguments [build_2x9mdgfer2n7ji1nsjr5g8ki6$_run_closure1@32b044f8] on project ':app' of type org.gradle.api.Project.
<a href="openFile:XXX/pluginTest/app/build.gradle">Open File</a>

报的错误


Paste_Image.png

在主gradle 添加如下配置:

buildscript {
    tasks.withType(JavaCompile) {
        sourceCompatibility = JavaVersion.VERSION_1_7
        targetCompatibility = JavaVersion.VERSION_1_7
    }
}

参考

  1. http://www.jianshu.com/p/873eaee38cc1
  2. http://www.jianshu.com/p/bcaf9a269d96
  3. http://kvh.io/cn/embrace-android-studio-gradle-plugin.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,178评论 19 139
  • 这篇文章讲给大家带来gradle打包系列中的高级用法-自己动手编写gradle插件。我们平常在做安卓开发时,都会在...
    呆萌狗和求疵喵阅读 16,220评论 22 80
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,539评论 25 709
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,165评论 6 342
  • 今天这3个故事都是关于人在面对困难的时候,选择哪种解决问题的方式往往是由你的处理问题的态度,你的心理承受...
    遇上缘阅读 1,693评论 0 0

友情链接更多精彩内容