So far, most Gradle articles start with the complexity of Gradle syntax. In fact, for Android people, mastering these syntax details is not useless. We just need to be able to understand them and look them up as we go. This article introduces Android Gradle according to the principle of ‘utility’. After reading this article, you should at least not be afraid of Build scripts.

If you are already familiar with build.gradle, you can refer to the Official Android Plugin DSL Reference.

Let’s start with a look at some files (folders) that are generated for Gradle by As.

As shown in the figure above, a standard As project consists of three major parts:

  • Top-level Gradle: Used to configure all Module properties
  • Moudle-level Gradle: Configures the properties of the independent Moudle
  • Gradle Wrapper: For a unified compilation environment, generally used by CI

Let’s look at it in detail.

Top-level Build Script

There are several concepts that come from Gradle Reference:

Gradle Script is all configuration scripts. This means that, when run, each script file eventually corresponds to an object in the program called a delegate object. For example, build.gradle corresponds to Project. Gradle has three types of proxy objects:

There is a built-in variable in any build.gradle —project.

We can view all of the built-in properties in the script using Gradle -q Properties.

Let’s look at the Top level Build Script step by step:

buildscript

Dependencies buildscript {repositories {jcenter ()} {the classpath 'com. Android. View the build: gradle: 2.2.0' / / NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }Copy the code

buildscript{}

Configures the build script classpath for this project.

The given closure is executed against this project’s ScriptHandler. The ScriptHandler is passed to The closure as The A closure ‘s delegate.

Delegates to:

ScriptHandler from buildscript

To put it simply, buildscript is the path to the class used to configure the buildscript. Internally, it passes configuration Closure to ScriptHandler (you don’t care what this is) and implements Settings Repositories and Dependencies.

Typically, this script block is written at the beginning, declaring dependencies that the script itself needs.

allprojects


allprojects {
    repositories {
        jcenter()
    }
}
Copy the code

allprojects{}

Configures this project and each of its sub-projects.

This method executes the given closure against this project and its sub-projects. The target Project is passed to the closure as the closure’s delegate.

Delegates to:

Each Project in allprojects

This Configuration closure will include the current project and all its sub-project implementations. The repositories you configure here will be available in all of these locations.

The notation here means that all projects look for dependencies in jCenter (). You can also specify flatDir, Maven, Ivy, and so on. You can refer to RepositoryHandler.

task clean


task clean(type: Delete) {
    delete rootProject.buildDir
}
Copy the code

This defines a new task called clean. Its type is Delete. In fact, the Android Plugin has the clean method built in, which is in the Module. The built-in clean method in the Module only cleans up the files in the Module and deletes the Build directory in the Module, but the build files in the project root directory are not cleaned up. So the clean method defined here is to delete the Build folder in the project directory.

Module-level Build Script

Module-level scripts are used to describe the compilation process for that module. Generally speaking, there are three types of Android that can be used:

  • Application: the correspondingcom.android.application. The result of compilation is an APK
  • The Android Library: correspondingcom.android.library. The compilation result is AAR
  • JavaLibrary: correspondingjava. The compiled result is JAR

Have you ever wondered how many plug-ins there are for Android? Take a look at the Google Android Plugin repository

Library and com.android. Application content configuration is not too much, here to com.android. Application as an example.

Because most of the module-level Build scripts are implemented by the plugin itself, we can’t find them in gradle documents. We need to search for refs in Google department (see Refs).

Are you wondering how many properties this file has? You can look at the source of this file

android


android {
    compileSdkVersion 24
    ....
}
Copy the code

The application plugin supports many more attributes than this.

apply plugin: 'com.android.application' android {/** * set build SDK and build tool version */ compileSdkVersion 24 buildToolsVersion "24.0.3" /** * For signatures, please refer to the official Google documentation:Sign Your App*/ signingConfigs {/** * As will automatically sign us with the Debug certificate. */ debug {} /** * Since the module-level Build Script also needs to be managed in VCS, The general practice is to set the environment variables locally and then read them as shown in the following codeTo rule outOutside the VCS, * At this point, also set the password as a variable in the file, */ release {storeFile file("$system.env.store_file ") storePassword "$system.env.store_password "keyAlias KEY_ALIAS" keyPassword "$system.env. KEY_PASSWORD"}} /** * sets the default values for all builds. About the build variant, */ defaultConfig {applicationId "com.walfud. myApplication "minSdkVersion 23 targetSdkVersion 24 VersionCode versionName 1 "1.0" testInstrumentationRunner "android. Support. The test. The runner. AndroidJUnitRunner"} / * * * type Defaults to debug and release. This is true whether you write or not. * In general, we leave the default values in debug, enable obfuscation in release, And use the private signature */ buildTypes {debug {// use the default} release {// confuse minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' // signingConfig signingConfigs.release}} /** * flavor */ productFlavors {m360 {} xiaomi {}} /** *The official said: The monocultures will create multiple APKs more effectively than those from Flavor. // That includes all splits and other options. // The value of those splits will be split into two categories. "Xxxhdpi ", "400dpi", "560dpi", "tvdpi"} // In this case we can specify the architecture we want to use by 'include'. 'Armeabi-v7a' universalApk true}}} /** * dependencies of this project */ ** * 'fileTree' */ compile fileTree(dir: 'libs', include: ['*.jar']) /** * To import the aar, we need to specify the location of the AAR, as shown in 'Repositories', in the * module-level libs directory. */ compile(name: 'components', ext: 'aar')} /** * Configates where to find this module-dependent file */ repositories {flatDir {dirs 'libs'}}Copy the code
Build Variant

Simply put, it is to automatically generate corresponding APK for different channels or versions. BuildType * productFlavor * density * abi does a cartesian product.

For priority, refer to Google’s documentation on Build Variants.

Part 2 – Gradle in As

1. Automatic download

Use default Gradle Wrapper (recommended) setting is used every time the project is re-imported, So As downloads the gradle version specified by distributionUrl in gradle-wrapper.properties. The process is extremely slow across the country. My advice is to find the above file and change the distributionUrl to a downloaded version of Gradle (for example, if you have downloaded Gradle-2.14.1 before) so that you can open it directly.

In fact, this configuration item is located in the configuration file (.idea/gradle.xml) automatically generated by the As. Let’s see:

For a New Project (‘ File -> New -> New Project ‘), As gives us this:

It looks like this in Settings:

As helps me define the Gradle version. Of course, if the specified gradle version does not exist, it will be downloaded.

Now look at the items that are ‘File -> Open’ but are not Reopen:

That is, every time you Open a project, the As will ignore the gradle version you set up and use the wrapper version specified in the wrapper file. So the reason why your clone code will block for a long time the first time you open it is because they are downloading Gradle in wrapper…

2. gradle-wrapper.properties

Gradlew. Bat and gradlew. Sh files in the root directory. These files read gradle/wrapper/gradle-wrapper.properties and compile with the gradle version specified therein. In general, this mechanism is used in CI servers to ensure that each compilation is in the same environment.


#Wed Nov 11 21:08:45 CST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
Copy the code

GRADLE_USER_HOME Defaults to your USER_HOME/. Gradle (c:\Users\\. Gradle in Win, ~/. Gradle in Linux).

For Gradlew, if the above path does not find an executable Gradle file, it will be downloaded and executed using the URL specified in distributionUrl.

3. gradle.properties

The main function is to configure some properties related to gradle compilation on the current machine. These properties are determined by each compilation machine (for example, how much memory is allocated) and therefore not suitable for git.

3.1 Property is divided into two types

3.1.1. system property

Similar to system environment variables. As a JVM startup parameter.

a) Set

# gradle.properties
systemProp.xxx=yyy
Copy the code

The system Property is modeled on Systemprop. XXX.

Only the top – levelgradle.propertyTo set the System Property.

The system provides the following built-in variables:

Org.gradle. daemon Whether to enable daemon. In general, it is recommended to turn native compilation on and turn it off on CI.

Org.gradle.java. home Specifies the Java home of the gradle process. There’s no use for eggs.

Org.gradle. jvmargs JVM parameters for daemon processes. You can adjust this parameter when compiling an error in OOM (see example below)

Org. Gradle. Configureondemand Google itself. No eggs with

Org.gradle. Parallel compilation between projects

Of course, we can also set the system property by specifying -d on the command line.

b) Get

// build.gradle
System.properties['xxx']
Copy the code

3.1.2. project property

Typically used as a variable inside a project to hold private values such as username and password.

a) Set

# gradle.properties
xxx=yyy
Copy the code

You can also set the project property by specifying -p on the command line

b) Get

// build.gradle
println xxx
Copy the code

3.2. Set the proxy


systemProp.https.proxyHost=www.proxyhost.org
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=userid
systemProp.https.proxyPassword=password
systemProp.https.nonProxyHosts=*.nonproxyrepos.com|localhost
Copy the code

3.3. Priority (higher priority below)

Gradle.properties in the project directory

$GRADLE_USER_HOME/gradle.properties

Environment variables or command line Settings using -dsystem. property or -pproject. property

The usual ‘What the hell is this?’

transitive = true

The compile (' com. Crashlytics. SDK. The android: answers: 1.3.10 @ aar ') {transitive = true; }Copy the code

Simply put, because the statement uses @aar notation, Gradle only downloads the AAR file without the dependency files needed to download the AAR. Therefore, transitive is required so that dependencies can be downloaded automatically. In general, there is no problem with removing @aar and {transitive = true}.

Refs:

In general, Google articles will tell you how to configure the effect, while Gradle articles will tell you how to configure the effect. Personal blogs are used to get through quickly.

Individual department:

Understanding Android (1) : Gradle details

Google is:

Android official: New Build System

Configure Your Build

Android Plugin for Gradle Release Notes

Android Plugin DSL (With this, mom is no longer afraid that I can’t find the function)

Android Plugin source repository

com.android.applicationThe source of

Bintray repository for Android Plugin

Gradle system:

Gradle Build Language Reference

Variable in gradle.properties: The Build Environment

Related