开发效率优化之自动化构建系统Gradle(二)上篇

 

阿里P7移动互联网架构师进阶视频(每日更新中)免费学习请点击:https://space.bilibili.com/474380680html

本篇文章将如下两个内容来介绍自动化构建系统Gradle:java

  • gradle 与 android gradle 插件的关系
  • Gradle Transform API 的基本使用

1、gradle 与 android gradle 插件的关系

1.1名词解释:

1.1.1,Gradleandroid

Gradle是一种构建工具,它使用一种基于Groovy的特定领域语言(DSL)来构建项目。不单单用于android 工程的构建。git

1.1.2,Android Plugin for Gradlegithub

这就是为了编译android 工程而开发的插件。下面就是申明Android Gradle 插件的位置。(build.gradle)api

buildscript {
  ...
  dependencies {
    classpath 'com.android.tools.build:gradle:2.2.0'
  }
}

1.2 gradle 与 android gradle

1.2.1,gradle 各版本源码地址架构

http://services.gradle.org/distributions/app

1.2.2, google 官网 gradle 插件 与 gradle 版本对照地址ide

https://developer.android.google.cn/studio/releases/gradle-plugin#updating-plugin工具

 

 
19956127-3229a752fd9b4dbd.jpg
 

 

1.2.3,gradle 版本与google gradle 插件版本的区别

在gradle wrapper.properties 中写的是 gradle 版本。

distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

在build.gradle 中依赖的是 gradle插件版本。

dependencies {
    //[this is the android gradle plugin version]
    classpath 'com.android.tools.build:gradle:3.1.0'
    

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

2、Gradle Transform API 的基本使用

2.1什么是Transform

官方API文档: http://google.github.io/android-gradle-dsl/javadoc/2.1/com/android/build/api/transform/Transform.html

咱们编译Android项目时,若是咱们想拿到编译时产生的Class文件,并在生成Dex以前作一些处理,咱们能够经过编写一个Transform来接收这些输入(编译产生的Class文件),并向已经产生的输入中添加一些东西。

咱们能够经过Gradle插件来注册咱们编写的Transform。注册后的Transform会被Gradle包装成一个Gradle Task,这个TransForm Task会在java compile Task执行完毕后运行。

对于编写Transform的API, 咱们能够经过引入下面这个依赖来使用:

compile 'com.android.tools.build:gradle:2.3.3'  //版本应该在 2.x以上

先大体看一下Transform的执行流程图:

 
2934684-c3b79e94df238eb8.png
 

2.2 Transform的使用场景

通常咱们使用Transform会有下面两种场景

  1. 咱们须要对编译class文件作自定义的处理。
  2. 咱们须要读取编译产生的class文件,作一些其余事情,可是不须要修改它。

接下来咱们就来看一下这些Transform API吧 :

2.3 Transform API学习

咱们编写一个自定义的transform须要继承Transform,它是一个抽象类, 咱们这里先看一下Transform的抽象方法:

public abstract class Transform {
    public abstract String getName();

    public abstract Set<ContentType> getInputTypes();

    public abstract Set<? super Scope> getScopes();

    public abstract boolean isIncremental(); // 是否支持增量编译
}

getName()就是指定自定义的Transform的名字。

2.4 输入的类型

Set<ContentType> getInputTypes()是指明你自定义的这个Transform处理的输入类型,输入类型共有如下几种:

enum DefaultContentType implements ContentType {
        /**
         * The content is compiled Java code. This can be in a Jar file or in a folder. If
         * in a folder, it is expected to in sub-folders matching package names.
         */
        CLASSES(0x01),

        /**
         * The content is standard Java resources.
         */
        RESOURCES(0x02);
    }

即分为class文件或者java资源。class文件来自于jar或者文件夹。资源就是标准的java资源。

2.5 输入文件所属的范围 Scope

getScopes()用来指明自定的Transform的输入文件所属的范围, 这是由于gradle是支持多工程编译的。总共有如下几种:

/**
     * This indicates what the content represents, so that Transforms can apply to only part(s)
     * of the classes or resources that the build manipulates.
     */
    enum Scope implements ScopeType {
        /** Only the project content */
        PROJECT(0x01), //只是当前工程的代码
        /** Only the project's local dependencies (local jars) */
        PROJECT_LOCAL_DEPS(0x02), // 工程的本地jar
        /** Only the sub-projects. */
        SUB_PROJECTS(0x04),  // 只包含子工工程
        /** Only the sub-projects's local dependencies (local jars). */
        SUB_PROJECTS_LOCAL_DEPS(0x08),
        /** Only the external libraries */
        EXTERNAL_LIBRARIES(0x10),
        /** Code that is being tested by the current variant, including dependencies */
        TESTED_CODE(0x20),
        /** Local or remote dependencies that are provided-only */
        PROVIDED_ONLY(0x40);
    }

对于getScopes()的返回,其实TransformManager已经为咱们定义了一些,好比:

public static final Set<Scope> SCOPE_FULL_PROJECT = Sets.immutableEnumSet(
            Scope.PROJECT, Scope.PROJECT_LOCAL_DEPS, Scope.SUB_PROJECTS, Scope.SUB_PROJECTS_LOCAL_DEPS, Scope.EXTERNAL_LIBRARIES);

若是一个Transform不想处理任何输入,只是想查看输入的内容,那么只需在getScopes()返回一个空集合,在getReferencedScopes()返回想要接收的范围。

public Set<? super Scope> getReferencedScopes() {
        return ImmutableSet.of();
    }

2.6 transform()

它是Transform的关键方法:

public void transform(@NonNull TransformInvocation transformInvocation) {}

它是一个空实现,input的内容将会打包成一个TransformInvocation对象,由于咱们要想使用input,咱们须要详细了解一下TransformInvocation参数。

2.7 TransformInvocation

咱们看一下这个类相关的API:

public interface TransformInvocation {

    Collection<TransformInput> getInputs(); // 输入做为 TransformInput 返回

    TransformOutputProvider getOutputProvider(); //TransformOutputProvider 能够用来建立输出内容

    boolean isIncremental();
}

public interface TransformInput {
    Collection<JarInput> getJarInputs();
    Collection<DirectoryInput> getDirectoryInputs();
}

public interface JarInput extends QualifiedContent {

    File getFile(); //jar文件

    Set<ContentType> getContentTypes(); // 是class仍是resource

    Set<? super Scope> getScopes();  //属于Scope:
}

DirectoryInput与JarInput定义基本相同。

public interface TransformOutputProvider {
    //根据 name、ContentType、QualifiedContent.Scope返回对应的文件( jar / directory)
    File getContentLocation(String name, Set<QualifiedContent.ContentType> types, Set<? super QualifiedContent.Scope> scopes, Format format);
}

即咱们能够经过TransformInvocation来获取输入,同时也得到了输出的功能。举个例子,

public void transform(TransformInvocation invocation) {
        for (TransformInput input : invocation.getInputs()) {
            input.getJarInputs().parallelStream().forEach(jarInput -> {
            File src = jarInput.getFile();
            JarFile jarFile = new JarFile(file);
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                //处理
            }
        }
    }

上面这段代码就是获取jar的输入,而后遍历每个jar作一些自定义的处理。

咱们在作完自定义的处理后,若是想本身输出一些东西怎么办? 好比一个class文件,就能够经过TransformOutputProvider来完成。好比下面这段代码:

File dest = invocation.getOutputProvider().getContentLocation("susion", TransformManager.CONTENT_CLASS, ImmutableSet.of(QualifiedContent.Scope.PROJECT), Format.DIRECTORY;

这段代码就是在本工程(ImmutableSet.of(QualifiedContent.Scope.PROJECT))下产生一个目录(Format.DIRECTORY), 目录的名字是(susion),里面的内容是TransformManager.CONTENT_CLASS

建立这个文件夹后,咱们就能够向其中写入一些内容,好比class文件。

2.8 注册Transform

咱们在了解transform api后,咱们能够编写一个自定义的Transform。可是咱们编写的这个Transform,如何在构建过程当中生效呢?咱们须要注册它

在自定义插件中注册它,而后在build.gradleapply就能够了。

//MyCustomPlgin.groovy
public class MyCustomPlgin implements Plugin<Project> {

    @Override
    public void apply(Project project) {
        project.getExtensions().findByType(BaseExtension.class)
                .registerTransform(new MyCustomTransform());
    }
}

其实若是你包含了你编写的transform库,咱们也能够直接在build.gradle中注册:

//在build.gradle中也是能够直接编写 groovy代码的。
project.extensions.findByType(BaseExtension.class).registerTransform(new MyCustomTransform());

参考:https://www.jianshu.com/p/031b62d02607
https://my.oschina.net/u/592116/blog/1851743

阿里P7移动互联网架构师进阶视频(每日更新中)免费学习请点击:https://space.bilibili.com/474380680

结束语

但愿读到这的您能转发分享和关注一下我,之后还会持续分享阿里P7 Android高级架构进阶知识点及解析,您的支持就是我最大的动力!!

 
18452536-f9647b6e16a958ff.jpg
相关文章
相关标签/搜索