Android detailed study of the configuration of Gradle

When graduation less than two years, my friends slowly got to have car and house have a girlfriend weekend has its own program, and I think I have a lot of good things out of reach, you can not find something to do to be happy, mood very bad. But at the same time I feel that precipitation takes time, effort, patience and self-discipline, so I always believe that the time is always difficult in the past to meet their total arrival of a better life, give yourself a shout: "Come on!."

Well, complaints made over, I recently watched "Android Gradle Definitive Guide" This book, though written in the book content may be relatively simple, but for Android developers should be quite enough for the. So, today I'm going to combine knowledge and develop their own projects on the books as an example to summarize the knowledge base article on the main points of Gradle.

Acquaintance Gradle
Gradle is a project of Apache Ant and Apache Maven based automation concepts construction tools. It uses a Groovy-based domain-specific language to declare the project settings, rather than the traditional XML. It supports the current language is limited to Java, Groovy and Scala, plan for the future will support more languages.

How to see above all a very official explanation for the entry of people it is simply a nightmare interpretation (including the old me). Here I will talk about that as I understand it in simple language.

Gradle is the project management, help us do rely on, package, deploy, publish, various sources of difference management. For example describe, if I were a young master to do great things usually unable to manage so many little things that Gradle is a thoughtful secretary or housekeeper, put some hodgepodge of little things to help us do a good job, so that we can feel at ease to play Code, other things can be left to the housekeeper tube.

That someone will ask, since the work can be done to him, why should we have to understand. I think we have to do things housekeeper, but also issued our command, we need to know these commands and butler preferences in order to get along in harmony with him, or you do not know it was wrong under the command of temperament, but it is very serious consequences.

In the time before practice, I use eclipse, it is to import the module online to download a required step by step import. However, since the use of Android Studio, Gradle very intimate help me complete this complex work, and often only need to add a word, it's amazing, when I think so, here we will be speaking about this.

Analysis
Here I used in the project with their own Gradle slowly Analysis:


We see that each Module will correspond to a Gradle file, in addition to a main Gradle Project's global document management. Here we take a look at that document called gradle-wrapper.properties of:

wrapper-Gradle
Wrapper is Gradle layer of packaging, to facilitate unified version Gradle build a team in the development process, so that everyone can use a unified version Gradle build.

The above chart we see that Gradle provides a built-in Wrapper task to help us to automatically generate the required Wrapper catalog file. Look at our Android project file automatically generated inside
finally, we know that these automatically generated file was originally created out of Gradle Wrapper.
Here we look at the role that this document gradle-wrapper.properties

See individual properties inside the project, the following look at the role of each property we actually should be most concerned about distributionUrl this property, he is download Gradle path, it will download stuff to see it in the following folder this folder contains the versions you download Gradle.
When I was a beginner when always encounter a problem, and that is the figure below:

When the project has been imported will stay in this interface, which is why? In fact, the reason is very simple, it is Gradle version of your favorite programs with Gradle version you import new project caused by inconsistent, how to solve? I was my own doing:
good speed when the Internet or science, by its own to download, but the download time is long or short, can not be guaranteed.
Speed limit when you are in the company, of course, my most common, is to replace your recently used files off the project gradle-wrapper.properties the file you want to import the project, basically I was solved, of course, sometimes encounter circumstances replace the error, but relatively small.
settings.gradle
Let's talk about settings.gradle file, it is actually used for initialization and configuration of the project tree, placed in the root directory of the project.

Most of the action is to configure the settings file from the project. In Gradle many projects are represented by the project tree, the equivalent of Project and Module concept we saw in Android Studio same. Android Studio project equivalent to the root of the Project, a project can have many root from the project, which is a lot Module, so that the Android Studio Module concepts and definitions correspond.

We can see this project we have added seven module, one to one, if you add a project depend on the project, it will appear in this document them.
Well, after we finished settings.gradle file slowly into the other documents, but we need to explain what is Groovy:

Groovy
Groovy dynamic language for the JVM is based on a virtual machine, and its syntax is very similar to Java, the Java learning Groovy basically no entry barriers. Groovy is fully compatible with Java, and on this basis a lot more flexible and dynamic type features, such as support for secret security, support for DSL, you can say it is a very flexible and dynamic scripting language.

At first I always put Gradle Groovy and confused, and now I always figure out their relationship. Gradle like a software, Groovy language is to write the software, which is very simple and clear it. Here we talk about the content that is written in Groovy syntax, but this knowledge I temporarily not science, are interested can go to a small partner to find out more in-depth Groovy syntax.

build.gradle (Project)
Here we have to say something about the Lord build.gradle file:

We are here, in terms of four labels:
1.buildscript
buildscript declaration in the script itself is a resource gradle want to use. Resources can be declared, including dependencies, third-party plug-ins, maven repository address, etc.

2.ext
ext is the custom attributes, many people like to have all the information about the version on another ext use their new gradle file centralized management, the following is how I explain ext use:


First, we create two files, respectively called build.gradle and version.gradle

It was then marked with the corresponding code in the two files

Finally Terminal mobile Android Studio to run the task the appropriate file folder.
We can find very amazing, when we enter the file build.gradle apply from: information 'version.gradle' words, we will be able to read the files in the ext.

I was now in the project this way the unified management of all third-party plug-in version, interested friends can try.

3.repositories
the name suggests is the meaning of the warehouse friends, and jcenter (), maven () and google () is the platform for hosting third-party plug-ins

4.dependencies
course equipped warehouse is not enough, we also need dependencies {} configuration in which, with the need to configure the dependent classpath configuration, because the dependencies in buildscript {} inside, so on behalf of the Gradle require plug-ins.

Let's look at another part of the code build.gradle (Project) of


allprojects
Repositories allprojects blocks for constructing multiple projects, provide a common dependencies required for all items. The subprojects can configure their own repositories for their own independence required dependencies.

Strange, someone will ask, why the same build.gradle (Project) file buildscript and allprojects inside the content of it is essentially the same, the difference between them where?

buildscript and allprojects role and the difference between
buildscript the declaration is required to use their own resources gradle script, that he is the steward of resources they need, to tell you the young master really does not matter. The statement is allprojects all the resources you need to use the module, that young master if you need to use each module with a third library, you can declare in allprojects inside. Under this interpretation should be able to understand it.

Well, here to talk about the last piece of code build.gradle (Project) file a


When running gradle clean, executed here defined task. The task inherited from Delete, delete the root directory of the build directory. Equivalent to executing Delete.delete (rootProject.buildDir). In fact, the implementation of this task is to be deleted Build files generated, with a clean Android Studio is a reason.

build.gradle (Module)
finished Project build file, just to say something about the last and most content files.

apply plugin

First, the say apply plugin: '×××'
This is called introduction Gradle plug, and plug Gradle roughly divided into two types:

apply plugin: '×××': is called binary plug, the plug-in binary usually is packaged in a jar in a separate publication, such as our custom plug-ins, and then released when we can assign plugin id, this plugin id preferably a fully qualified name, just like your package name;
the apply from: '×××': application scripting plug-in is called, in fact, this can not be considered a plug-in, it's just a script. Application scripting plug-ins, in fact, this script loaded in, and binary plug is different is that it uses is from keywords. Goblets immediately following a script file can be local, may also be present in the network, if the network to use the words of HTTP URL. Although it is not a true plug-in, but can not ignore its role. it is a script file modular basis, we can put a huge script file is divided into blocks, the segment finishing. split into one common, clear responsibilities of file, then use to apply from referring to them, for example, we can put commonly used functions in a Utils.gradle script, other scripts for file references. Example we App version name and version number placed in a separate script file, clear, simple, convenient and fast. We can also use the automated processing of the file is automatically generated version.
Gradle plugin to talk about the role of
the plug-in application to your project, the plugin will extend the functionality of the program to help you do a lot of things during the construction project. 1. You can add tasks to your project, to help you complete some Zhi situation, such as testing, compile, package. 2. You can add dependencies to configure your project, we can rely on our project need to configure the build process through them. For example, we compile time dependent on third-party libraries. 3. You can add a new extension properties, methods, and other items to an existing object type, so you can use them to help us configure and optimize the build, such android {} This block is an extension of Android Gradle plugin adds to the Project Object . 4.

Then we talk about the 'com.android.application'
Category Android Gradle plugin is actually based on Android engineering attribute categories. There are three categories in the engineering Andriod, one is the App application engineering, it can generate a running application apk: one is the Library project, which can generate AAR public works contracted out to other App, just as our Jar , but it contains information Android resources, it is a special packet Jar; last category is test test Engineering, App for engineering works or the library unit test.

App plug-in the above mentioned id: com.android.application.
Library plug the above mentioned id: com.android.library.
The Test Plug-id: com.android.test.
On average, a project will set up an App plug-in module and is usually set to the Library plug-ins.


android {}
is an extension of the type provided by the plug Android, it allows us to customize Android Gradle project, is the only entrance Android Gradle project configuration.

compileSdkVersion
is compiled depend on the version of the Android SDK, here is the API Level.

buildToolsVersion
is to build the Android works with build tools version.

{} defaultConfig
defaultConfig is the default configuration, which is a ProductFlavor. ProductFlavor allows us to generate a plurality of different packet apk while depending on the situation.

applicationId
configure our package name, package name is the unique identifier app, in fact, he and AndroidManifest inside the package is different, and there is no direct relationship between them.

package refers under code directory path; applicationId refers to the unique identification app is released, we will sign the application third-party libraries, released when used.

minSdkVersion
is api level supported by the Android system, here is 15, which means that less than 15 versions of Android models can not use this app.

targetSdkVersion
show that we are developing based on which version of Android, here is 22.

versionCode
that our app application build number, generally used to control app upgrade, of course, I use the bugly can receive an automatic upgrade upgrade push is based on this.

versionName
show version of our app application name, usually released when written on the app tells the user, so that when you fix a bug and updated version, people say how they found you this bug still, this time you I can confidently tell his own version of the app look. (Personal experience when tear force can calmly deal)

multiDexEnabled
used to configure whether to automatically split the BuildType plurality of Dex enabled. General application in the code too much, more than 65,535 methods of the time.

ndk {}
multiple platforms compile, so there is time to use the package, the platform comprising four 'armeabi', 'x86', 'armeabi-v7a', 'mips'. The general use of the SDK provided by third parties, it may be included with the library so.

sourceSets
source code collection that is used to describe a Java plug-in source code and abstract concept and management of resources, is a set of Java source code files and resource files, we can change the set of Java source directory or directories and other resources by sourceSets.

Such as on the map, I passed sourceSets told me Gradle storage path jni so on the package in the app / libs, and told him compile time to find their own.


name: build type name
 
applicationIdSuffix: application id suffix
 
versionNameSuffix: version name suffix
 
debuggable: whether to generate a debug the APK
 
minifyEnabled: Are confusion
 
proguardFiles: confusion file
 
signingConfig: Signature configuration
 
manifestPlaceholders: list placeholder
 
shrinkResources: whether to remove the untapped resources The default false, meaning not removed.
 
zipAlignEnable: zipalign whether to use compression tool.
 
multiDexEnabled: whether to split into multiple Dex
 
multiDexKeepFile: specified text file is compiled into the main Dex file
 
multiDexKeepProguard: confusion specified file is compiled into the main Dex file
buildType
building type, Android Gradle project, which has helped us built debug and release two a building type, the two modes is that the major car do not, and whether the signature is not the same debugging on a device, other codes and file resources are the same. Generally used in code obfuscation, confusion designated file directory on the lower diagram, minifyEnabled = true opens confusion:

signingConfigs
signature configuration, a app only be released after the signing, installation, use, protection app signature is a way of marking the uniqueness of the app. If the app is malicious deletion, the signature is not the same, you can not install the upgrade, to a certain extent to protect our app. The signingConfigs very convenient to provide the signature configuration for us. storeFile signature files, password storePassword signature certificate file, storeType signed certificate type, keyAlias signed certificate keys alias, keyPassword signed certificate to change the password key.

By default, the signature debug mode has been configured, debug certificate is automatically generated using the Android SDK, which is usually located in $ HOME / .android / debug.keystore, its key and password are already known, in general, we do not need a separate configuration signature information debug mode.


productFlavors
he is Gradle multi-channel package in my opinion, you can define different variables of different packages to achieve their own customized versions of the demand.

manifestPlaceholders
placeholder, we can dynamically configure some content AndroidManifest file through it, such as app name:


See in the figure, we can find that we define the manifestPlaceholders in productFlavors = [APP_NAME: "(Test)"] Thereafter, the label AndroidManifest plus "$ {APP_NAME}", we can control the playing out of each packet we want to name different names, such as test server and the production server package should not the same name.
buildConfigField
He is a function BuildConfig file, and BuildConfig this class is Android Gradle build scripts generated after compilation. The buildConfigField is one of the custom function variables, see the figure we define three constants:


We can see that we have three variables declared in BuildConfig file

Then we can control these variables in your code with different versions of the code:
We add this if, you can easily control test and production versions of the pay issue, no longer have to manually change to change, and that the question is, how do I go to choose a different version of it, look:

If you are Android Studio, you can choose Build Variants find your current version to compile it.
flavorDimensions
the name suggests is a dimension, Gradle3.0 later use flavorDimensions variables must be defined in order to use {} in defaultConfig, or will be error:

Error:All flavors must now belong to a named flavor dimension.
The flavor 'flavor_name' is not assigned to a flavor dimension.

So that we can form different applicationId and versionName in different packages.

dexOptions {}
we know, Android Java source code is compiled into byte code class, in packaged into apk dx is optimized when the virtual machine commands into executable Android DEX files. DEX file more compact, racking their brains to do this Android DEX format, it is to make our program run faster on the Android platform. For these processes and documents generated DEX treatment, Android Gradle plugins to help us deal with the, Android Gradle plugin SDK will call the dx command to be processed. But sometimes you may encounter prompt memory errors, exceptions are prompted to roughly java, lang.OutOfMemoryError: GC overhead limit exceeded , why would prompt memory of it? In fact, this is just a dx command script that calls or written in Java dx.jar library is a Java program processing, so when out of memory, we will see this Java exception message. By default, the memory allocated to dx It is a G8, which is 1024MB.

So we just need a bigger memory settings, we can solve this problem, put the project on my memory map is set to 4g.


dependencies {}
we usually use most probably this,

First, a first compile fileTree (include: [ '* .jar'], dir: 'libs'), the extension of the jar after such local configuration libs folder will be dependent, very convenient.
If you want to introduce a local module, then the need to use compile project ( '×××').
If you want to introduce online repository of dependency, we need to write compile group: 'com.squareup.okhttp3', name : 'okhttp', version: '3.0.1', of course, this is the most complete version, abbreviated put group , name, version removed, and then a ":" to split. compile 'com.squareup.okhttp3: okhttp: 3.0.1'

But the gradle3.0 after build.gradle is dependent default implementation, compile but not before. In addition, dependent instructions api. So here we are concerned that:
Gradle 3.0 implementation dependent, api difference: the
fact api no difference with the previous compile, will compile all into api is wrong; and implementation dependent instruction is not passed, but also That third-party libraries currently referenced in this module is limited to the use, need to add another module used to rely on, with the following two graphs illustrate:

I believe people will read the map at a glance. Well, this issue of content written about it, what if the above errors and omissions in the content, then welcome to give me a raise. Although only told gradle several files, but felt a little niche content not write it, if necessary later, I'll make up on. Today talk so much, next goodbye!

Author: 19snow93https: //juejin.im/post/5aeeb542f265da0b7e0c29f1
--------------------- 
Author: Loongxu 
Source: CSDN 
Original: https: //blog.csdn .net / heng615975867 / article / details /  80346723
copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Published 48 original articles · won praise 45 · views 60000 +

Guess you like

Origin blog.csdn.net/hubianyu/article/details/84548653