Gradle plugin自定义

详见我的简书 http://www.jianshu.com/p/c8b3f6f829bb

背景

最近组里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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值