[Android Pro] Gradle tips#2-Syntax

Source: Internet
Author: User
Tags jcenter

Referece to:http://blog.csdn.net/lzyzsd/article/details/46935063

In my first blog, I explained the different stages of tasks and task in the build process. After writing this article, I realized that I should tell the gradle in more detail. It's important to understand grammar so that we don't have to run into a complex build script to get the dishes straight. I'll explain some grammatical things in this article.

Grammar

The Gradle script is written using the groovy language. Groovy's syntax is a bit like Java, and I hope you can accept it.
If you are familiar with groovy, you can skip this section.
There's a very important concept in groovy that you need to understand. –closure (closures)

Closures

Closure is the key to our understanding of gradle. Closure is a separate block of code that can receive parameters, return values, or be assigned to variables. and Java callable interface, future similar, also like a function pointer, you how convenient to understand all good ...

The point is that the code executes when you call it, not when it's created. Look at an example of a closure:

def myclosure = {println ' Hello world! '} Execute our closuremyclosure () #output: Hello world!

The following is a closure for receiving parameters:

def myclosure = {String str--println str}//execute our closuremyclosure (' Hello world! ') #output: Hello world!

If closure only receives one parameter, it can be used to refer to this parameter:

def myclosure = {println It}//execute our closuremyclosure (' Hello world! ') #output: Hello world!

Closure to receive multiple parameters:

def myclosure = {String str, int num--println "$STR: $num"}//execute our closuremyclosure (' My String ', +) #output: My string:21

In addition, the type of the parameter is optional, the above example can be abbreviated to this:

def myclosure = {str, num-and println "$STR: $num" }//Execute our closuremyclosure (' My Strin G ',21

It's cool that the variables in the current context can be used in closure. By default, the current context is the class where closure was created:

def myVar = ' Hello world! '  = {println myvar}myclosure () #output: HelloWorld!

Another cool point is that the context of closure can be changed by Closure#setdelegate (). This feature is useful:

// I ' m referencing MyVar from MyClass class New MyClass () myclosure.setdelegate (M) myclosure () class MyClass {    = ' Hello from myclass! ' } #output: Hello from MyClass!

As you see in the lock, MyVar does not exist when creating closure. This is not a problem, because when we execute closure, MyVar exists in the context of closure. In this example. MyVar is present, because I changed its context for m before executing the closure.

Pass the closure as a parameter

The benefit of closure is that it can be passed to different methods, which can help us decouple the execution logic. In the previous example I have shown how to pass closure to an instance of a class. Below we will look at the various methods of receiving closure as parameters:

1. Receive only one parameter, and the parameter is closure method: MyMethod (Myclosure)
2. If the method receives only one parameter, the parentheses can be omitted: MyMethod myclosure
3. You can use the inline Closure:mymethod {println ' Hello world '}
4. Method of receiving two parameters: MyMethod (arg1, Myclosure)
5. Similar to 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 '}

Here I just want to remind you that the 3 and 6 are not look familiar?

Gradle

Now that we know the basic syntax, how do we use it in the Gradle script? Let's look at the following example:

Buildscript {    repositories {        jcenter ()    }    dependencies {        ' com.android.tools.build: gradle:1.2.3 '    }}allprojects {    repositories {        jcenter ()    }}

Knowing groovy's syntax is not a good understanding of the above example?
The first is a Buildscript method, which receives a closure:

def buildscript (Closure Closure)

Next is the Allprojects method, which also receives a closure parameter:

    def allprojects (Closure Closure)

The others are similar ...

It looks much easier now, but it's still a bit confusing, and that's where these methods are defined. The answer is project.

Project

This is a key to understanding the Gradle script.

The statement block at the top of the build script will be delegated to the instance of project

That means project is where I'm going to find it.
Search the Buildscript method on the document page of project and find the buildscript{} script block. Wait, what's the script block? According to the documentation:

Script block is a method that only receives closure as a parameter

Continue reading the Buildscript documentation, which says delegates To:scripthandler from Buildscript. That is, the closure that we pass to the Buildscript method, the final execution context is scripthandler. In the example above, the closure that we passed to Buildscript called the repositories (closure) and dependencies (closure) methods. Since closure was entrusted to Scripthandler, we went to Scripthandler to find the dependencies method.

Found void dependencies (Closure configureclosure), according to the documentation, dependencies is used to configure the dependencies of the script. and dependencies finally entrusted to the Dependencyhandler.

See how extensive the use of Gradles is commissioned. It is important to understand the delegation.

Script blocks

By default, many script blocks are pre-defined in project, but the Gradle plugin allows us to define a new script blocks! ourselves
This means that if you send some {...} at the top of the build script, but you cannot find this script blocks or method in Gradle's documentation, in most cases this is a script block defined in the plugin.

Android Script Block

Let's take a look at the default Android App/build.gradle file:

 Apply plugin: ' com.android.application ' android {compilesdkversion  22 Span style= "color: #000000;" > buildtoolsversion  "22.0.1"  Defaultconfig {ApplicationID " com.t Rickyandroid.testapp " minsdkversion  16 ta Rgetsdkversion  22 Versioncode  1 ve Rsionname  "1.0" } buildtypes {release {minifyenabled false   Proguardfiles Getdefaultproguardfile (  ' Proguard-android.txt '), ' Proguard-rules.pro '  '}}  

As we can see, it seems like there should is Android method which accepts Closure as a parameter. But if we try to search for such method in Project Documentation-we won ' t find any. And the reason for are simple-there is no such method:)

If you look closely to the build script-you can see that before we execute Android method-we apply Com.android.applica tion plugin! And that ' s the answer! Android Application Plugin extends Project object with Android script block (which is simply a method which accepts Closur E and delegates it to appextension Class1).

As you can see, here's an Android method that receives a closure parameter. But if we search in the document of project, we can't find this method. The reason is simple, and this is not the method defined in project.
Looking closely at the build script, you can see that we used the Com.android.application plugin before the Android method was redeemed. The Android application plugin extends the project object and adds the Android Script block.
Where can I find the documentation for the Android plugin? Android Tools website or here

If we open the Appextension document, we can find the properties of the method used in the build script:
1.compileSdkVersion 22. If we search for compilesdkversion, this property will be found. Here we assign a value of "22" to this property.
2.buildToolsVersion and 1 Similar
3.defaultConfig-is a script block that will be delegated to the Productflavor class to execute.
4. Other
Now that we can understand the syntax of the Gradle script, we know how to find the document.

[Android Pro] Gradle tips#2-Syntax

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.