What is gradle script from a programming perspective ?? Android Studio script construction and Programming

Source: Internet
Author: User
Tags artifactory

What is gradle script from a programming perspective ?? Android Studio script construction and Programming

As the Android development environment changes from Eclipse to Android Studio, each of us has begun to have more or less access to gradle scripts. Most people regard gradle as a build tool. If there is a problem, I do not know how to proceed with the analysis, you can only hope that Baidu can find a solution.

If we regard gradle as a programming framework and clarify the relationship between gradle scripts and gradle objects, we can not only clearly understand the gradle script, but also no longer use Baidu in case of problems, you can easily solve the problem by reading the document.

This article uses the most common gradle project to show you how to understand the gradle script in Android by reading the api documentation.

1. gradle Introduction

Gradle is based on groovy, while groovy is an extension based on java. It is fully compatible with java class libraries, therefore, you can use the java language you are familiar with to program gralde scripts. At the end of this article, we will provide an example of using java programming directly in the gradle script.

As this article only allows everyone to understand the script, rather than writing it by themselves, the details of groovy and gradle are not the focus of this Article. If you need them, Baidu. The point here is that function calling in groovy is similar to java, but it can omit parentheses, especially when its last parameter is a closure.

Println ("aaa") // This is acceptable,

Println "aaa" // No problem either.

Did you find a secret: All functions are called in the gradle script !!

Gradle api documentation path:Https://docs.gradle.org/current/dsl/

Because we also use the Android plug-in, we also need the plug-in documentation. This document is special. It is a git project. online browsing always displays the html source code rather than the page, so I suggest you clone it back to the local, and then open it in a browser, Project address: https://github.com/google/android-gradle-dsl.git

 

Ii. Relationship between gradle scripts and gradle classes

After browsing the gradle document, we will find that the gradle script in the project actually corresponds to the gradle object:

1. Gradle: Global Object. One gradle build corresponds to one Gradle object;

2. Project: Each Project is a Project object, which corresponds to a build. gradle file;

3. Settings: corresponds to a Setting. gradle file;

4. task: indicates the work to be executed. A Project has one or more tasks used to complete the construction. The Project organizes the construction process by reasonably setting dependencies between tasks, complete the final build task.

 

Iii. Script Execution Process and object generation

1. Each time gradle is called for execution, it will be a Gradle object, which stores some global information;

2. The setting. gradle will be parsed to generate the Settings object. Generally, the setting. gradle mainly calls the include method and imports the sub-modules of the project;

3. Execute build. gradle of each sub-Project to be imported, and generate and configure the Project object;

Generally, in build. gradle, The apply method of the Project is called to introduce the plug-in to define various attributes and create required tasks in the plug-in.

 

Iv. instance resolution

Take the default app sample project structure of Android studio as an example. The gradle Script directory structure contained in the project is as follows:

1. setting. gradle

Setting. gradle has only one line of statements:

Include': App'

The include here is actually a function of Setting, and ': app' is a parameter of function call.

What else can we write in setting. gradle? Because setting. gradle corresponds to the Settings object in gradle, then check the Settings document (https://docs.gradle.org/current/dsl/org.gradle.api.initialization.Settings.html), to see what methods it has, what properties, you know in setting. what can gradle write:

For example:

Include': Common'

Project (': Common'). ProjectDir =NewFile (settingsDir,'../SDK/Common /') // After the include call,: CommonOfProjectObject,Project (': common ')Retrieve this object and setProjectOfProjectDirAttribute.

Then projectDirWhere did they come from? SeeProjectClass documentation.

 

2. build. gradle

Next let's take a look at build. gradle. build. gradle corresponds to a Project object, and the Project itself is a Build script:

What can BuildScript contain?

Have you seen many old friends? Buildscript, dependencies ..

After reading this, we should be able to understand what can be written in build. gradle.

Buildscript,During execution of any build. gradle, buildscript is first processed. It is used to create a runtime environment for the script.What is the runtime environment?

In general, it is to download the required plug-ins. For example, android projects require android plug-ins, which are introduced in the following way:

Buildscript {

Repositories {// indicates which remote repository to download the plug-in if there is no cache locally

MavenCentral ()

}

Dependencies {

// This is the plug-in jar of applyplugin: com. android. application.

Classpath'Com. android. tools. build: gradle: 1.3.0'

// NOTE: Do not place your application dependencies here; theybelong

// In the individual module build. gradle files

}

}

Repositories {// indicates which remote repository to download the dependent library during compilation if there is no cache locally

MavenCentral ()

}

The above repositories and dependencies are all function calls ~~

Have you seen the two identical repositories above? Their functions are different. In buildscript, the plug-in initialization environment is used to set the plug-in download repository, in addition, this is used to set the download repository of some remote libraries on which the project depends.

Introducing plug-ins in build. gradle is a common action:

Apply plugin:'Com. android. application'

Check the Project documentation (https://docs.gradle.org/current/dsl/org.gradle.api.Project.html). apply is a method of the Project,

3. android

See the android plug-in documentation: (file: // home/test/android-gradle-dsl/1.5/index.html)

The above is the information about all the blocks that can be written in android {}, and then what can be written in each block. Click to view the attributes and methods,

For example, signingConfigs:

SigningConfigs {

Release {

StoreFile file ('../Sign/release. jks')

StorePassword"[Email protected]! D"

KeyAlias"Small"

KeyPassword"[Email protected]! D"

}

}

This article can come to an end now. I believe that you can understand the meaning of each code block in the gradle script in combination with this document.

V. parent-child relationship between Android Projects

In the above example project structure, there is a parent-child relationship between projects, such as RxJava-Android-Samples/build. the Project corresponding to gradle is RxJava-Android-Samples/app/build. the father of the Project corresponding to gradle, and the operations performed in the parent Project will be inherited by the Project. For example, if the android plug-in has been introduced in the parent Project, it can be referenced directly in the sub-Project without rewriting a buildscript block.

1. RxJava-Android-Samples/build. gradle

Buildscript {

Repositories {

MavenCentral ()

}

Dependencies {

Classpath'Com. android. tools. build: gradle: 1.3.0'

// NOTE: Do not place your application dependencies here; theybelong

// In the individual module build. gradle files

}

}

Allprojects {

Repositories {

MavenCentral ()

}

}

 

2. RxJava-Android-Samples/app/build. gradle

// Directly reference the android plug-in, without the buildscript preparation plug-in;

Apply plugin:'Com. android. application'

Dependencies {

Compile'Com. android. support: support-v13: 23.0.1'

Compile'IO. reactivex: rxandroid: 1.0.1'

// BecauseRxAndroid releases are few and far between, it is recommended you also

// Explicitly depend on RxJava 'slatest version for bug fixes and new features.

Compile'IO. reactivex: rxjava: 1.0.14'

Compile'IO. reactivex: rxjava-math: 1.0.0'

Compile'Com. jakewharton. rxbinding: 0.2.0'

Compile'Com. jakewharton: butterknife: 5.1.1'

Compile'Com. jakewharton. timber: 2.4.2'

Compile'Com. squareup. Adjust fit: Invalid fit: 1.6.1'

Compile'Com. squareup. okhttp: 2.0.0'

Compile'Com. squareup. okhttp: okhttp-urlconnection: 2.0.0'

Compile'Com. alibaba: fastjson: 1.2.4'

DebugCompile'Com. squareup. leakcanary: leakcanary-android: 8080'

ReleaseCompile'Com. squareup. leakcanary: leakcanary-android-no-op: 8080'

}

Android {

CompileSdkVersion 23

BuildToolsVersion'23. 123'

DefaultConfig {

ApplicationId"Com. morihacky. android. rxjava"

MinSdkVersion14

TargetSdkVersion22

VersionCode1

VersionName"1.0"

}

BuildTypes {

Release {

MinifyEnabledTrue

Proguardfilesgetdefadefaproguardfile ('Proguard-android.txt'),'Proguard-rules. Pro'

}

}

}

6. Examples of java programming in gradle

The editor is not very friendly with the code.

1. build. gradle

Buildscript {

Repositories {

Maven {

Url 'HTTP: // artifactory.rnd.meizu.com/artifactory/all'

}

}

Dependencies {

Classpath 'org. aspectj: aspectjtools: 1.8.6'

}

}

Importorg. aspectj. bridge. IMessage

Import org. aspectj. bridge. MessageHandler

Importorg. aspectj. tools. ajc. Main

Dependencies {

Compile 'org. aspectj: aspectjrt: 1.8.6'

}

Android. applicationVariants. all {variant->

JavaCompile javaCompile = variant. javaCompile

// Println javaCompile. properties

JavaCompile. doLast {

String [] args = [

"-ShowWeaveInfo ",

"-1.5 ",

"-Inpath", javaCompile. destinationDir. toString (),

"-Aspectpath", javaCompile. classpath. asPath,

"-D", javaCompile. destinationDir. toString (),

"-Classpath", javaCompile. classpath. asPath,

"-Bootclasspath", android. bootClasspath. join (File. pathSeparator)

]

MessageHandler handler = newMessageHandler (true );

New Main (). run (args, handler)

Def log = project. logger

For (IMessage message: handler. getMessages (null, true )){

Switch (message. getKind ()){

Case IMessage. ABORT:

Case IMessage. ERROR:

Case IMessage. FAIL:

Log. error message. message, message. thrown

Break;

Case IMessage. WARNING:

Case IMessage. INFO:

Log.info message. message, message. thrown

Break;

Case IMessage. DEBUG:

Log. debug message. message, message. thrown

Break;

}

}

Println "aspect args:" + args. toString ()

}

}

2. groovy

The following code shows variables, function definitions, List, Map, Range, and closure in groovy.

1) variable definition

Defvariable1 = 1 // You can end with a semicolon.

2) function definition;

StringtestFunction (arg1, arg2) {// you do not need to specify the parameter type

...

}

3) List variables are defined by [], such

DefaList = [5, 'string', true] // The List is defined by [], and its element can be any object.

4) List access

AList [100] = 100 // set the value of 101st elements to 10

AssertaList [100] = 100

5) Map variables are defined by [:], such

DefaMap = ['key1': 'value1', 'key2': true]

Map is defined by [:]. Note the colon. The left side of the colon is the key, and the right side is the Value. The key must be a string and the value can be any object. In addition, you can use ''or" "to pack the key, or use quotation marks. For example:

DefaNewMap = [key1: "value", key2: true] // The key1 and key2 are processed as strings "key1" and "key2" by default"

However, if the Key is not enclosed in quotation marks, it will also bring some confusion, such

Defkey1 = "wowo"

DefaConfusedMap = [key1: "who am I? "]

// Is key1 in aConfuseMap "key1" or is the value of key1 "wowo "? Obviously, the answer is the string "key1 ". If it is "wowo", the definition of aConfusedMap must be set:

DefaConfusedMap = [(key1): "who am I? "]

6) for the Range class, variables of the Range type are represented by the begin value + two vertices + the end value.

Def aRange = 1 .. 5

// If you do not want to include the last element

DefaRangeWithoutEnd = 1 .. <5

// Contains the four elements: 1, 2, 3, and 4.

7) Closure

Defxxx = {paramters-> code} // or

Defxxx = {No parameter, pure code}

For example:

Defgreeting = {"Hello, $ it! "}

Assertgreeting ('Patrick ') = 'hello, Patrick! '

Parentheses can be omitted if the last parameter of a function is a closure;

Public static List Each (List Self, Closure closure)

The above function indicates that closure is called for processing every element of the List. The closure here is a bit of a callback function. However, when using this each function, what Closure should we pass in? For example:

Def iamList = [1, 2, 4, 5] // defines a List

IamList. each {// call its each. The format of this Code cannot be understood, right? Each is a function. Where are Parentheses?

Println it

}

The above Code has the following knowledge points:

The parentheses for calling the each function are missing! Originally, in Groovy, when the last parameter of a function is a closure, parentheses can be omitted. For example

DeftestClosure (int a1, String b1, Closure closure ){

// Dosomething

Closure () // call the closure

}

You can skip the brackets when calling the SDK!

TestClosure4, "test ",{

Println "I am in closure"

}

Start your Gradle build and programming journey ~~

Related Article

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.