Android Gradle learning series (7)-Detailed and practical combat of the Gradle core Task

Foreword

In this article, we talk Gradleabout another important conceptTask

1. TaskDefinition and configuration

1.1 TaskDefinition

The first: can be directly taskdefined by the function

Insert picture description here

Insert picture description here

The second kind: the TaskContainer
Insert picture description here
is the one we circled with a red frame above, how to create it? Just call the createmethod directly
Insert picture description here

Insert picture description here
What is the difference between these two methods? In fact, the first method will eventually be added to TaskContainerit, which is TaskContainerequivalent to our Taskmanagement class.Since it is a management class, it can be created not only, let us look at its source code

@HasInternalProtocol
public interface TaskContainer extends TaskCollection<Task>, PolymorphicDomainObjectContainer<Task> {
	...
    @Nullable
    Task findByPath(String path);

    Task getByPath(String path) throws UnknownTaskException;

    <T extends Task> T create(String name, Class<T> type, Action<? super T> configuration) throws InvalidUserDataException;

    TaskProvider<Task> register(String name, Action<? super Task> configurationAction) throws InvalidUserDataException;

    Task replace(String name);
    ...

After reading the source code, we found that it is TaskContainermainly to find and add, and we rarely use other

1.2 TaskConfiguration

For example, we want to taskconfigure the group name and description for our

The first type: we directly configure it when it is defined.
Insert picture description here
The second type: call various configuration methods in the configuration code block
Insert picture description here

The same groupings taskwill be put together. Let ’s see
Insert picture description here
what we can taskconfigure? Let ’s go to the Tasksource code and see.
Insert picture description here

2. TaskDetailed execution

Insert picture description here
We found that when we execute helloTaskthis task, it will also print out helloTask2the output content. Why? It is very simple, because they are executed in the configuration phase, so how do we make them execute in the execution phase? Call doFirstor doLastmethod
Insert picture description here
Let us see the result
Insert picture description here

First doFirstand doLastreally executed in the execution stage is then performed on the outside doFirstor doLastto take precedence over the closure, the two methods can gradleprovided already taskextended

Below we will count our buildtime under actual combat
:

  • 1. Define two variables: start execution time and execution end time, the difference between the two is the result we want
  • 2. Find the first one to be executed task, call the doFirstmethod and get the start time
  • 3. Find the last executed task, execute doLastmethod, get the end time
  • 4. The difference between the two.
    Insert picture description here
    We print to see how long it will take
    Insert picture description here

3. TaskDependency and execution order

Insert picture description here

3.1 TaskDependence

We first define three. task
Insert picture description here
We first execute nothing and taskC
Insert picture description here
only output it taskC. We will compare it with this later . What do
we want to do for our taskCspecified dependency?

The first one: add at the time of definition dependsOn, just like we added groupbefore

Insert picture description here
Add multiple need to use the array
Insert picture description here
we executetaskC
Insert picture description here

The second: call dependsOnmethod

Insert picture description here

The third: dynamic dependence

Here we will create a few more for demonstrationtask

Insert picture description here

Then we used TaskContainerthe findAllmethod to find me in line with ours task, and then taskCrely on them
Insert picture description here

We executetaskC
Insert picture description here

3.2 Taskinput and output

Insert picture description here
TaskInputs: The Taskinput class can be any data type and file
TaskOutputs: The Taskoutput class can only be a file or folder, and it can also be used as another Task. TaskInputs
Below we write a small example to learn these two methods.
Suppose we want to output a xmlfile. The content includes the version number and version information.First of
Insert picture description here
all, we create three extended attributes:
Insert picture description here
here we also need to define one File, which is ours release.xml, if it does not exist, we manually create it
Insert picture description here

Then we started to implement our read and write functions. Correspondingly, we need to create two task, writeTaskand readTask
we write first . We need writeTask
to pass the three attributes we defined earlier to ourtask

    inputs.property('versionCode', this.versionCode)
    inputs.property('versionName', this.versionName)
    inputs.property('versionInfo', this.versionInfo)

Also specify the output

    //为task指定输出
    outputs.file this.destFile

Here's start writing real logic, this logic written doLast{}in

task writeTask {
    inputs.property('versionCode', this.versionCode)
    inputs.property('versionName', this.versionName)
    inputs.property('versionInfo', this.versionInfo)
    outputs.file this.destFile
    doLast {
    	// 返回一个map
        def data = inputs.getProperties() 
        File file = outputs.getFiles().getSingleFile()
        // 将map转为实体对象
        def versionMsg = new VersionMsg(data)
        def sw = new StringWriter()
        def xmlBuilder = new MarkupBuilder(sw)
        // 文件中没有内容
        if (file.text != null && file.text.size() <= 0) { 
            // 将xml数据写入到sw中
            xmlBuilder.releases { // <releases>
                release { // <releases>的子节点<release>
                    versionCode(versionMsg.versionCode)
                    // <release>的子节点<versionCode>1.0.0<versionCode>
                    versionName(versionMsg.versionName)
                    versionInfo(versionMsg.versionInfo)
                }
            }
            // 将sw里的内容写到文件中
            file.withWriter { writer ->
                writer.append(sw.toString())
            }
        } else { // 已经有其它版本信息了
            xmlBuilder.release {
                versionCode(versionMsg.versionCode)
                versionName(versionMsg.versionName)
                versionInfo(versionMsg.versionInfo)
            }
            def lines = file.readLines()
            def lengths = lines.size() - 1
            file.withWriter { writer ->
                lines.eachWithIndex { String line, int index ->
                    if (index != lengths) {
                        writer.append(line + '\r\n')
                    } else if (index == lengths) {
                        writer.append(sw.toString() + '\r\n')
                        writer.append(line + '\r\n')
                    }
                }
            }
        }
    }
}

task readTask {
    inputs.file destFile
    doLast {
        def file = inputs.files.singleFile
        println file.text
    }
}

Then write a test that taskdepends on these twotask

task taskTest(dependsOn: [writeTask, readTask]) {
    doLast {
        println '任务执行完毕'
    }
}

Here is a place to note, the writeTaskorder of execution is a priority in readTaskthe

3.3 TaskBy APIspecifying the execution order

  • mustRunAfter: Forced to askexecute after one or some t is executed.
  • shouldRunAfter: Same mustRunAfteras the function, but not mandatory.

Here we create a few taskto practice
Insert picture description here

Here we enforce the order taskX, taskY, taskZ
the order of the output to the next we look upset
Insert picture description here

4. Attach to the build life cycle

This is similar to what we explained before to get the build time. Here we execute our custom project after the project is built.task
Insert picture description here

5. TaskType of

This we need to go to gradlethe official website to get to know at the
official website
open official website, found on the left sideTask types
Insert picture description here

Like we said beforeCopy
Insert picture description here

Published 87 original articles · Like 319 · Visit 1.49 million +

Guess you like

Origin blog.csdn.net/Greathfs/article/details/102809361