Understanding and configuring Gradle in Android Studio

Source: Internet
Author: User
Tags jcenter

When building Android apps using Gradle, you always need a file like this: Build.gradle. You should have read this file, and if you haven't, you can look at it now, it doesn't have much content. Its simplicity is due to its many default values for settings and properties. Gradle is based on groovy language, but using it to build a common project, you can not learn groovy, if you want to deeply do a custom build plug-in, you can consider groovy, because it is based on Java, so you have the Java Foundation, Learning is not difficult.

This blog is intended for anyone who can read Android studio's Gradle scripts, mainly from Gradle's simple syntax, gradle scripts's script structure, every script (Build.gradle, Settings.gradle), the role of each of the scripts in terms of meaning and other aspects of gradle scripts.

1.projects, tasks and action

Yes, engineering, tasks and behavior. A project must have at least one project, a project must have at least one task, a task consists of some action. If Project is more abstract, it can be understood that a build.gradle corresponds to a project, and the action is like a method in Java, which is a collection of code. During the engineering build process, Gradle generates the corresponding project and task based on the configuration information in the Build.gradle.

Project is essentially a collection of tasks, each of which performs some work, such as compiling a class file, extracting files, deleting files, and so on.

1.1 Build process

1.1.1 Initialization phase. You will first create a project object and then execute the Build.gradle configuration object. If there is more than one module in a project, it means that there will be more than one project, and you will need multiple build.gradle.

1.1.2 Configuration phase. At this stage, the configuration script is executed, and the new task is created and configured to the project object during execution.

1.1.3 Execution phase. At this stage, the task created by the configuration phase is executed, and the order of execution depends on the parameters passed in and the current directory when the script is started.

1.2 Task

The task identifies a logical execution unit, and you may have used it many times without knowing that you are aware of it. When you re-compile the project, a task called build is used, and when you clean up the project, you will use a task called clear (as you'll see later), and Gradle has prepared a lot of tasks for you, which can be viewed using gradle tasks, for example, Here are some of the things that are listed here:

Assemble-assembles all variants of any applications and secondary packages.build-assembles and tests this Project.buil Ddependents-assembles and tests this project and all projects the depend on It.buildneeded-assembles and tests this p Roject and all projects it depends on.clean-deletes the build directory.

In addition, you can declare a task yourself, like this:

Task haha {    println "haha"}
Then use the gradle haha command to print out the haha. Here, haha this task is executed, so that task is an execution unit. You can also use the following methods to define a task:

Task Hello << {    println "Hello World"}
This is different from the former, "<<" means to add some action to hello this task is actually called the Dolast method of the task, so it is equivalent to the following code:

Task Hello {    dolast{        println "Hello World"    }}


As for the difference between haha and hello, you can also deepen the impact:

First, go to your project directory, execute Gradle (there are no parameters later, in addition, at this time, build.gradle in both hello and haha two tasks), the results are as follows:

E:\android\androidwork2.0\gradletest>gradlehahaincremental Java Compilation is an incubating feature.:helpWelcome To Gradle 2.13.To run a build, run Gradle <task> ... To see a list of available tasks, run Gradle Tasksto see a list of command-line options, run Gradle--helpto See more Deta Il about a task, run Gradle help--task <task>build successfultotal time:21.877 Secse:\android\androidwork2.0\gradl Etest>gradle Tasks

can be pressed to Haha, is printed, and Hello is not printed, note that this time the default task is help, that is, do not execute haha this task, but it is still printed, it means that the use of definition haha this way defined task is executed during the initialization phase , and tasks defined using the Define Hello method are not executed until the execution phase.

There is such a task in the top-level build.gradle of Android Studio:

Task Clean (type:delete) {    Delete Rootproject.builddir}
You can see that this task has a type type,task there are a number of types that come out with some of the following:
Here is the delete type, the type of task can be understood as follows: Task Chinese is mission, there are many kinds of tasks, delete is to say that this is a task to delete files.

This is not a more in-depth discussion of the task, which has allowed us to understand what is being encountered in Android studio.

2.closures2.1 definition closure Understanding gradle need to first understand the concept of closure, closure is a block of code, code block generally with {} wrapped, so the definition of closure can be as follows:
def haha = {println ' haha! '} Haha () #output: haha!
You can see that a closure can be thought of as a block of code, but it can be called as a function, and it can accept parameters such as the following:
def myclosure = {String str--println str}myclosure (' haha! ') #output: haha!
So this closure has parameters, and multiple parameters only need to be added in front of it. 2.2 Delegate Another cool point is that the context of closure can be changed by Closure#setdelegate (). This feature is useful:
def myclosure = {println MyVar}//i ' m referencing MyVar from MyClass classmyclass hello = new MyClass () Myclosure.setdelega Te (hello) myclosure () class MyClass {    def myVar = ' Hello from myclass! '} #output: Hello from myclass!
As shown above, when creating closure, MyVar does not exist. But it doesn't matter, because MyVar exists in the context of closure when executing closure. In this example. MyVar is present, since its context was changed before the execution of the closure for the hello.
2.3 Closures as parameter closures can be passed as parameters, and the following are some cases of closures as parameters:
1. Receive only one parameter, and the parameter is closure method: MyMethod (Myclosure) 2. If the method receives only one argument, the parentheses can be omitted: MyMethod myclosure 3. You can use inline Closure:mymethod { println ' Hello World ' 4. Methods to receive two parameters: MyMethod (arg1, Myclosure) 5. and 4, the singular closure is inline: MyMethod (arg1, {println ' Hello world '}) 6. If the last parameter is closure, it can be taken from the parentheses: MyMethod (arg1) {println ' Hello world '}

3.gradle DSL

DSL (Domain specific Language), Chinese meaning is the language of a particular domain. Gradle DSL is the language of the Gradle domain. In order to better understand gradle, it is necessary to learn Gradle DSL. Gradle's script is very brief, but it has its syntax, and if you don't understand the DSL, even if you know how to modify the script to get the results you want, you won't understand why it's changed.

3.1 Basic Concepts you must know

First. The Gradle script is a configuration scripting that configures a specific object when the script is executed. For example, in an Android studio project, when Build.gradle is executed, it configures a project object and Settings.gradle is executed when it configures a settings object. Project,settings This object is called a delegate object, which shows the different delegate objects corresponding to different scripts:


Second. Each gradle script implements a script interface, which means that the methods and properties defined in the script interface can be used in scripts.

3.2 Structure of the build script

A build script consists of 0 or more statements and script blocks. The following is a description of them, in order to avoid translation errors, here to paste the original.

A build script is made up by zero or more statements and script blocks. Statements can include method calls, property assignments, and local variable definitions. A script block is a method call which takes a closure as a parameter. The closure is treated as a configuration closure which configures some delegate object as it executes. The top level script blocks is listed below.

Approximate meaning statments can include method invocation, attribute assignment, local variable definition, and script Bolck is a method whose parameters can be a closure. This closure is a configuration closure because it is used to configure the delegate object when it is executed. Take the Build.gradle of Android Studio for example:

Apply plugin: ' Com.android.application ' android {    compilesdkversion    buildtoolsversion "23.0.3"    defaultconfig {        ApplicationID "com.konka.gradletest"        minsdkversion        targetsdkversion        Versioncode 1        versionname "1.0"    }    buildtypes {        release {            minifyenabled false            Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '        }    }}dependencies {    Compile Filetree (dir: ' Libs ', include: [' *.jar '])}

Plugin' com.android.application '
The above is a statements, where apply is a method, followed by its parameters.   This line of statement is difficult to understand because it uses the abbreviation, write all should be like this:

Project.apply ([plugin: ' Com.android.application '])
Does that make it clear? Project calls the Apply method, passing in a map as a parameter, the map key is plugin, and the value is com.android.application.

dependencies {    Compile filetree (dir: ' Libs ', include: [' *.jar '])}

It is a script block above, but it is difficult to understand, the reason is so difficult to understand, because Gradle grammar with a lot of shorthand, dependencies write complete should be like this:

Project.dependencies ({Add (' compile ', ' com.android.tools.build:gradle:2.0. ', {//Configuration statements})})

We know that block is a closure, and here first calls the dependencies method under project, the parameter of this method is a closure, and the closure is passed to Dependencyhandler,dependencyhandler with a method: add , this add has three parameters, namely ' compile ', ' ... ' and a closure.



The following top-level build script block is in the Gradle:


Let's take allprojects{} for example, and say how the script block works:

allprojects {    repositories {        jcenter ()    }}

Allprojects{} is typically a script block in the top-level build.gradle, which is a method that accepts a closure as a parameter. The Gradle tool creates a project object, which is a delegate object (delegate object), which is created later, Build.gradle is executed, the process of execution, the allproject{} method is called, and the parameter of this method is a closure, The closure is then executed to configure the project object.

4.Understanding the Gradle files

Once you understand the concept of project,task and action, you can understand the Gradle configuration file. There are typically three profiles in the Android Studio project, each with its own features. The location of the three files should look like this:


When building a project, the following sequence is available:

1. Create a Settings object.

2. Check if settings.gradle exists, does not exist and does nothing, it is used to configure the Settings object.

3. Create a Project object using the Settings object, which creates a series of project in a multi-module project.

4. Check that the Build.gradle is present and use it to configure the project object if it exists.

4.1 Settings.gradle

If a new project contains only one Android app, then Settings.gradle should look like this:

Include ': App '
If there is only one app in your project, then the Settings.gradle file is not allowed. Include ': App ' app indicates the module name you want to build, Android Studio's default module designer app, you can change the name of the app directory, such as Hello, Then you have to change the app in Settings.gradle to Hello. This will be a very meaningful attempt, because with this attempt, you will be able to modify the file as you wish. For example, modify it like this:



So this time you must have tried to build multiple apps at once? If you have done before, then you are very good, you do not have to look, if you have not tried, then try it with me:

The first step: Right-click on your project and select New Mudole.

Step Two: you have succeeded!

Yes, it's that simple, now look at the look of the project:


Yes, this time, Settings.gradle, he is the name of our new module, which is actually the name of a directory under the project top level directory. You can change the name, you can add the module.

Note: The settings.gradle is actually read into the initialization phase, and a settings object is generated after reading, and then some methods of this object are called. You don't need to know this object, you know it's there to help you understand the process of building a project.

4.2 The top-level build file

is the top-level build.gradle script. The configuration content in this file will be applied to all modules (we have created two module, one hello, one gradletest2) in the previous step. Therefore, the common attributes in each module are configured in the top-level build.gradle, which defaults to the following:

<pre style= "font-family: Song body; font-size:9pt; Background-color:rgb (255, 255, 255); " ><pre name= "code" class= "java" >buildscript {    repositories {        jcenter ()    }    dependencies {        classpath ' com.android.tools.build:gradle:2.0.0 '        //Note:do not place your application dependencies here; they Belong        //In the individual module Build.gradle files    }}allprojects {    repositories {        jcenter ()    }} Task Clean (type:delete) {    Delete Rootproject.builddir}

This script is made up of Buildscript {},allprojects{} Two script blocks, Buildsctipt is a top-level build script block, As said in 2.2, is a method, the parameter is a closure, the closure of a few script blocks, these script bolck is also a method, parameters are also a closure. Eventually these closures are executed to configure the corresponding delegate object. For example, the closure of this method calls the Jcenter method, which configures the remote repository of the Gradle and, when configured, repositories in the remote repository if dependencies are missing during the construction process. The configuration in the top-level build.gradle is applied to all projects, and the top-level Build.gradle delegate object is root project, The Build.gradle in the sub-project directory corresponds to its own project, in short, a build.gradle corresponds to a project.

As for the meaning of each script block, it can be literally guessed, such as allprojects {} is to configure the contents of the closure for all project, this is the configuration of the remote warehouse, there are many kinds of warehouses, want to use the other warehouse can be modified here. buildsctipt{} is a tool for all project configuration building repositories, and the dependecbies{} is the information for the configuration builder, from which you can see that the build tool is Gradle, and the version is 2.0.0; Modify the version of the Gradle can be changed here. But the information from the name alone is not enough, in order to get more information, you can look at "Gradle for Android" this book.


4.3 Build.gradle under sub-engineering

Apply plugin: ' Com.android.application ' android {    compilesdkversion    buildtoolsversion "23.0.3"    defaultconfig {        ApplicationID "com.konka.gradletest"        minsdkversion        targetsdkversion        Versioncode 1        versionname "1.0"    }    buildtypes {        release {            minifyenabled false            Proguardfiles getdefaultproguardfile (' proguard-android.txt '), ' Proguard-rules.pro '        }    }}dependencies {    Compile Filetree (dir: ' Libs ', include: [' *.jar '])    testcompile ' junit:junit:4.12 '    compile ' com.android.support:appcompat-v7:23.3.0 '}
4.3.1 The first line is a statement, call the Apply method, this method is defined as follows:

void Apply (map<string,?> options);

Its role is to check whether Gradle has declared this plugin, there is nothing to do, no words will make plug-ins available.


Each of the specific script blocks, most of them are methods, you can press CTRL + LEFT mouse button in Android studio, click to see its declaration, each method has comments to explain its role.

4.3.1 Android block

Android is the largest block in this script, it contains andoird-specific plug-ins that can be used because they were previously called

plugin ' Com.android.application ' ,
In addition, here is set up to compile the parameters for Android, build type and so on.
4.3.2 Dependencies Block
Dependecies is also a method of accepting closures as a parameter, which sets the dependencies for compiling the current app. If the current app relies on an external package, you can put the package under the Libs directory, then right-click on the Add as library, and you'll generate a compile ' ... ' 's record.
4.3.3 also has some other configurations, such as:
//This is the code to resolve the lint error Linto ptions {abortonerror False}//<span style= "font-family:arial, Helvetica, Sans-serif; font-size:9pt; " > Signature settings </span>signingconfigs {myconfigs {storefile file ("Signature files address") Keyalias "..." Keypassword "..." Storepassword "..."}}//<span style= "font-family:arial, Helvetica, Sans-serif; font-size:9pt; " > Obfuscation settings </span>buildtypes {release {signingconfig Signingconfigs.myconfigsrunproguard trueproguardfiles Getdefaultproguardfile (' Proguard-android.txt '), ' Proguard-rules.pro '}}//<span style= ' font-family:arial, Helvetica, Sans-serif; font-size:9pt; " > Channel packaging (different package name) </span>productflavors {aaa{applicationid = ' package name '}bbb{applicationid= ' package name '}}}//<span style= ' Font-family:arial, Helvetica, Sans-serif; font-size:9pt; " Import of >so files </span>task copynativelibs (type:copy) {from Filetree (dir: ' Libs ', include: ' armeabi/*.so ') into ' Build/lib '} 


Summary: All of the above shows the approximate process of a gradle work, the composition of the Gradle script, a general description of the features of each Gradle configuration script in Android studio, presumably explaining some of the role of script block. Since this blog is designed to understand how Android studio Gradle works and how scripts are structured, you can look at the book Gradle for Android If you want to understand the role of each script block in more detail. In addition, the following articles will also have a detailed discussion of the commonly used script block.



Understanding and configuring Gradle in Android Studio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.