Gradle entry - only this one

What is?

The syntax is based on the Groovy language ( Groovy is a JVM-based agile development language, can be simply understood as a strongly typed language java weakly typed version) in the project management is based on the concept of the project Ant and Maven tools automate construction .

Basics ready

Java-based, command-line basis using
official document : https://docs.gradle.org/current/dsl/
Gradle Guide: https://gradle.org/docs/current/userguide/userguide
Android plug-in documentation : HTTPS: / ... /github.com/google/android-gradle
AndroidGradle use the document : http://tools.android.com/tech-docs/new-build-system/user-guide
Groovy basis: HTTP: // Attis-Wong -163-com.iteye.com/blog/1239819
Delegate mechanism Groovy closures : https://www.cnblogs.com/zqlxtt/p/5741297.html

Gradle build the operating environment

  1. Gradle is running relies JVM, which is java runtime environment. So to install jdk and jre, Gradle like the current version of the operating environment in jdk 1.6 above, should now have to jdk 1.8 a.
  2. Then to the official website Gradle Gradle the archive now. Address , which this page has two methods for a manual installation An installation script. I generally like yourself, so in the future to clean up more convenient.
  3. After downloading the archive, extract, and then configure the environment variables manually installed jdk people should have a familiar configuration environment variable bar. Configuration environment variable is not the same at every platform

MacOS Configuration. In ~/.bash_profileadd the following code

#gradle  注意gradle-2.14.1是自己解压的路径
export GRADLE_HOME=${HOME}/gradle-2.14.1
PATH=${PATH}:${GRADLE_HOME}/bin
export PATH

After saving the input terminal source ~/.bash_profileEnter configuration just let the execution take effect. Then enter the command line gradle -vto see if the installation was successful.

$ gradle -v

------------------------------------------------------------
Gradle 2.14.1
------------------------------------------------------------

Build time:   2016-07-18 06:38:37 UTC
Revision:     d9e2113d9fb05a5caabba61798bdb8dfdca83719

Groovy:       2.4.4
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_111 (Oracle Corporation 25.111-b14)
OS:           Mac OS X 10.12.2 x86_64

Get a look HelloWorld

Create a test_graldefolder. Then create a folder inside build.gradlethe file. Note that the file names do not make plays. In build.gradleadd the following code:

task helloworld{
    doLast{
        println'Hello World!'
    }
}
#后者等同于下面的代码,
task helloworld2 <<{
    println "Hello World!"
}

Then run it:

liuqiangs-MacBook-Pro:test_gralde liuqiang$ gradle helloworld
:helloworld
Hello World!

BUILD SUCCESSFUL

Total time: 1.52 secs

This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.14.1/userguide/gradle_daemon.html

We analyze the steps. build.gradle is the default Gradle build script files, Gradle command execution time, it will default load build.gradle script file in the current directory, of course, you can also specify the file you want to load performed by the -b parameter. This is just a simple example of the task, followed by detailed common definition of the task.

The build script defines a task (Task), the task name is helloworld, and to add a task helloworld action, the official name of Action, Gradle read the source code you'll see it everywhere, in fact, he is some language Groovy closures , doLast achieve closure on this part of the code means that after the Task is finished to the callback doLast. The second method, "<<" represents the added code to execute in helloworld. As part of the grammar, the syntax is basically Groovy (including some syntactic sugar, which is a shorthand way of writing, if a write JavaScript or Python will be better understanding of some, but it is recommended to read about the basic grammar of groovy), plus some DSL (domain specific language) convention.

Execution flow and basic terminology

And, like Maven, Gradle simply provides a framework to build the project, the real work is the Plugin. Gradle by default provides us with many common Plugin, which includes building Plugin Java project, as well as Android and so on. The difference is that with Maven, Gradle does not provide a built-in project life cycle management, but java Plugin adds a number to the Project Task, these Task execution order for us to create a project like Maven as the build cycle.

Gradle is a declarative build tool. When executed, Gradle will not execute the order at the outset build.gradle contents of the file, but divided into two stages, the first stage is to configure the stage, and then the actual implementation phase.
Configuration phase, Gradle will read all the contents of all build.gradle files to configure Project and Task, etc., such as setting Property Project and Task, handling dependencies between Task and so on.

A look at the basic structure of the Android multi Moudule (ie gradle multi Project Multi-the Projects Build ) of the basic project structure.

├── app #Android App目录
│   ├── app.iml
│   ├── build #构建输出目录
│   ├── build.gradle #构建脚本
│   ├── libs #so相关库
│   ├── proguard-rules.pro #proguard混淆配置
│   └── src #源代码,资源等
├── module #Android 另外一个module目录
│   ├── module.iml
│   ├── build #构建输出目录
│   ├── build.gradle #构建脚本
│   ├── libs #so相关库
│   ├── proguard-rules.pro #proguard混淆配置
│   └── src #源代码,资源等
├── build
│   └── intermediates
├── build.gradle #工程构建文件
├── gradle
│   └── wrapper
├── gradle.properties #gradle的配置
├── gradlew #gradle wrapper linux shell脚本
├── gradlew.bat
├── LibSqlite.iml
├── local.properties #配置Androod SDK位置文件
└── settings.gradle #工程配置

The above project structure is complete in AndroidStudio, we abstracted into multiple Project Gradle look

├── app 
│   ├── build.gradle #构建脚本
├── module 
│   ├── build.gradle #构建脚本
├── build.gradle #工程构建文件
├── gradle
│   └── wrapper    #先不去管它
├── gradle.properties #gradle的配置
├── gradlew #gradle wrapper linux shell脚本
├── gradlew.bat
└── settings.gradle #工程配置
  • Gradle create a corresponding object for each build.gradle Project areas will, in the preparation of Gradle script, we are actually in operation Gradle domain objects such as Project. Multi-Project in the project, we will operate more Project target areas. Gradle provides a powerful multi-Project to build support.
  • To create a multi-Project of Gradle project, we first need to add the configuration file named settings.gradle in the root (Root) Project, the file should contain the name of each sub-Project. Gradle the Project can simply mapped to AndroidStudio in Module.
  • In the outermost build.gradle. Live is usually done: Configure the other sub-Project. For example, add some property as a child Project.
  • There is a project called settings.gradle in the root directory. This document is very important, the name must be settings.gradle. Inside it tells Gradle, this includes the number of sub-multiprojects Project (can be understood as AndroidStudio in Module).

Read Gradle configuration syntax

Gradle to provide us with a complete set of DSL, so in many cases we write the code seems to have been out of groovy, groovy but at the bottom is still performed so many rules of grammar or syntax of Groovy.
See build.gradle arranged under the app a AndroidStudio

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "me.febsky.demo"
        minSdkVersion 15
        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(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.1.0'
}

Analysis of the first rowapply plugin: 'com.android.application'

In fact, this sentence is Groovy syntactic sugar, like Ruby and Js have this syntactic sugar, apply actually a way to make up the script after the parentheses: apply (plugin: 'com.android.application')still looks a little awkward is not? There is a syntactic sugar, if the parameter is a map method of the type, then the square brackets may be omitted, further reducing apply([ plugin: 'com.android.application']), may not understand the wording see the map in Groovy, and as js. So this line means: apply actually a method to receive a parameter of type Map.

Two summary : 1. The method calls, parentheses can be omitted 2. If the method parameter is a Map, the square brackets can be omitted.

Groovy closure syntax language

Look above dependenciesthis is actually a method call. Project calls the method of dependencies. But the argument is a closure, the use of closures in the start of the article gives a link. We restore them at:

#方法调用省略了()我们加上
dependencies ({
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.1.0'
})

Tip point : if the closure is the last argument of the method, the closure can be placed outside the parentheses

#所以代码还能写成这样
dependencies (){
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.1.0'
}

Getter and Setter

Groovy language two concepts, Bean is a concept in Groovy, a mechanism is Delegate Groovy closures.
Java programmers certainly no stranger to the JavaBeans and Getter / Setter methods, is designed to get the properties / settings class. But in Groovy you do not have those useless up. That Groovy dynamic for each field will automatically generate getter and setter, and we can call the getter and setter like a field visit by itself. The Project object has Gradle such a version attribute (Property) The following two lines of code execution result is the same:

println project.version // Groovy  
println(project.getVersion()) // Java  

Project,Task ,Action

Gradle dependencies between the Project is based, instead of the entire Project Task.

Project: is the most important area of the object Gradle, we write build.gradle full effect of the script, in fact, configure a Project instance. In build.gradle script, we can implicitly manipulation Project examples, such as, apply plug-in, declare dependencies, such as the definition of Task, as above build.gradleshown. apply, dependencies, task, etc. is actually Project method, the parameter is a code block. Examples Project manipulation if desired, can also be displayed, such as:project.ext.myProp = 'myValue'

Task: is organized into a directed acyclic graph (DAG) . Gradle the Task either by different Plugin introduced, either directly in the creation of our own build.gradle file. Gradle ensure their dependence Task execution order, and each Task is performed only once at most.

Gradle by default provides several common Task for us, such as viewing of Project Properties, displays all the current Project Task defined and so on. : Command Line can view all of the Task Project by clicking $ gradle tasks(no specific log out stickers). You can see, Gradle by default it provides us dependencies、projects和propertiesand other Task. dependencies dependent information for displaying the Project, projects for displaying all Project, including the root and child Project Project, all the properties are used to display a Property Project included.

** Tips: ** View Project in all Task: $ gradle tasks
View Project in all properties:$ gradle properties

In the above build.gradleadd the following code:

task myTask {  
    doFirst {  
        println 'hello'  
    }  
    doLast {  
        println 'world'  
    }  
}  

The meaning of this code : Project to add a task called "myTask" of
using a closure to configure this task, Task offers doFirst and doLast method to add Action to yourself.

In fact, the true role of build.gradle script is to configure a Project instance. Before performing the build script, Gradle will be ready for our good a Project instance, after the execution of the script, Gradle will be followed by the implementation of tasks in the DAG.

Custom Task wording

Look at the following code file path ~/Test/build.gradle:

#1
task helloWorld << {
    println "Hello World"
}
#2 Test文件夹下建一个src目录,建一个dst目录,src目录下建立一个文件,命名为test.txt
task copyFile(type: Copy){
    from "src"
    into "dst"
}

The first helloWorld here is a DefaultTask type of the object, which is the default type is defined when a Task, of course, we can also explicitly declare the type Task, and even customize a Task type.
The second code (type: Copy) is the "type explicitly declare Task", Executive gradle copyFiletest.txt also went dst go.

If the task declaration allprojects in root in the Project of build.gradle () method, then the Task will apply to all of the Project.

The task dependencies

Gradle does not provide a built-in project life cycle management, but java Plugin adds a number to the Project Task, these Task execution order for us to create a project like Maven as the build cycle. Then the task is performed sequentially on how to use this dependency declarations taskA.dependsOn taskBlook at the code below:

task taskA << {
   println 'this is taskA from project 1'
}

task taskB << {
   println 'this is taskB from project 1'
}

taskA.dependsOn taskB

Then we run the command line:
$ gradle taskA
operating results will first execute print taskB, and then execute the print taskA

If Muliti-Project mode, with dependence Project belongs to, such as taskA.dependsOn ':other-project:taskC'where the taskC located in a different taskA Project, AndroidStudio respect, it is located in a different Module build.gradle, whereas for the other-project Module Name .

Task of type can be customized (no in-depth study)

Custom Plugin wording

No in-depth research, an online example given:

apply plugin: DateAndTimePlugin

dateAndTime {
    timeFormat = 'HH:mm:ss.SSS'
    dateFormat = 'MM/dd/yyyy'
}

class DateAndTimePlugin implements Plugin<Project> {
    //该接口定义了一个apply()方法,在该方法中,我们可以操作Project,
    //比如向其中加入Task,定义额外的Property等。
    void apply(Project project) {
        project.extensions.create("dateAndTime", DateAndTimePluginExtension)

        project.task('showTime') << {
            println "Current time is " + new Date().format(project.dateAndTime.timeFormat)
        }

        project.tasks.create('showDate') << {
            println "Current date is " + new Date().format(project.dateAndTime.dateFormat)
        }
    }
}
//每个Gradle的Project都维护了一个ExtenionContainer,
//我们可以通过project.extentions进行访问
//比如读取额外的Property和定义额外的Property等。
//向Project中定义了一个名为dateAndTime的extension
//并向其中加入了2个Property,分别为timeFormat和dateFormat
class DateAndTimePluginExtension {
    String timeFormat = "MM/dd/yyyyHH:mm:ss.SSS"
    String dateFormat = "yyyy-MM-dd"
}

Each Plugin custom interfaces are required to implement Plugin, in addition to Project Plugin written, we can also write other Gradle Plugin class. This interface defines an apply () method, in this method, we can operate the Project, for example, to which was added Task, define additional Property and so on.

Original Address

Gradle Wrapper

Wrapper, as the name suggests, in fact, to Gradle layer of packaging, to facilitate unified team in the Gradle build version of the development process, and then submitted to the git, then others can be downloaded, so that everyone can use a unified version Gradle build, avoid because Gradle version does not bring unity unnecessary problems. (So ​​to understand this thing can not, just to have a unified management, more convenient)

Generated wrapper

gradle built-generated wrapper task, we can execute the command line:
$ gradle wrapper

Directory structure is generated as follows (used AndroidStudio very familiar):

├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
└── gradlew.bat
  • gradlew and gradlew.bat are executable scripts under Linux and Window, their usage and Native Command gradle is the same, gradle how to use, how they will be used. Running under MacOS$ ./gradlew myTask
  • gradle-wrapper.jar specific business logic implementation the jar package, gradlew ultimately used to perform the operations associated gradle executed java jar package.
  • gradle-wrapper.properties configuration file is used to configure which version of gradle use, etc.

Detailed contents look gradle-wrapper.properties

#Sat Jan 21 14:02:40 CST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-bin.zip

It can be seen from the above contents and file names, which is a java profiles, see above is automatically generated, we can also manually modified. Then look at the meaning of each field:

  • distributionBase downloaded compressed decompression gradle primary storage directory
  • distributionPath respect distributionBase after decompression of compressed path gradle
  • zipStoreBase with distributionBase, just store the zip package
  • zipStorePath with distributionPath, just store the zip package
  • distributionUrl gradle release Download compressed package, which is the version you now this project will be dependent gradle of.

Generating wrapper can specify parameters

  • Generating content gradle-wrapper.properties wrapper can be specified by specifying the parameters.
  • Using the methods as gradle wrapper –gradle-version 2.14such, so that means we configure the wrapper using version 2.14 of gradle, it will affect gradle-wrapper.properties value distributionUrl in the Rules of the value is http://services.gradle.org/distributions/gradle - $ {} -bin.zip gradleVersion
  • If we do not add any parameters when calling gradle wrapper it, you will use your current version Gradle as gradle version wrapper generated. For example, your currently installed version of gradle is 2.10, the generated wrapper version is 2.10. Note: The current version refers to the version that environment variable configuration.

【参考文章】
http://www.infoq.com/cn/articles/android-in-depth-gradle/
http://blog.csdn.net/innost/article/details/48228651

Original Address: https: //www.jianshu.com/p/001abe1d8e95

Guess you like

Origin www.cnblogs.com/jpfss/p/11535883.html