Gradle compiled and packaged Android apk detailed introduction _android

Source: Internet
Author: User
Tags assert documentation

Gradle compiled and packaged Android apk detailed introduction

Understanding the Gradle build process and interpreting the configuration of the Android Gradle plug-in

Read this article must be used to generate APK gradle, the article will not tell how to install the running Gradle, if necessary, you can read the article at the end of the reference.

The APK package is a ZIP compression package that is found in the SDK documentation (/docs/tools/building/index.html) from the Java source code, the resource file to the build APK, and the compilation package for a series of specific procedures. And this series of specific processes, repetitive and tedious, build tool is to process these processes and liberate your hands. Ant as an early building tool for APK, the build process appears intuitive, like configuration, Gradle can be easily configured, but more like scripts, can be programmed.

Understanding Gradle Construction

1. Simple understanding of building tools

From a programmer's point of view, how do you write code to automate your apk generation process? First of all, you need to know the SDK, where the NDK, the Android project has several library engineering, their Java source code, resource files are respectively? The input parameters of the command line must not satisfy the requirement, which naturally comes to the mind of the configuration file. So your automation tool is to parse these profiles and follow the procedures that are required to generate APK files. Gradle is such a tool, the configuration file is your common settings.gradle,build.gradle, but he also provides more features, such as dependency management, Process control, as well as plug-in mechanism to customize your build process.

Gradle's programming language is groovy, and the configuration files it needs support groovy. The groovy language is JVM-like Java, and it's good for Java, so you can write extensions in Java code, write profiles like normal programming, rather than using XML to write configuration logic like Ant.

2.Groovy

Groovy's syntax, the thumbnail of its own code looks like a script, I just read a little bit of documentation, listing our common introduction:
First groovy is an object-oriented dynamic language.
(1) The semicolon can be omitted at the end of the statement
(2) The definition of a variable can be defined with Def, or it can be used directly
(3) Function definitions can be defined with DEF or not (with return value declarations)

function can omit parameter types
function calls can omit parentheses

Take a look at an example:

println ' Hello '                  
 
int power (int n) {2**n}             
 
println "2^6==${power (6)}" 

The first line of the output string Hello, the second line defines a function, the third line outputs the function call value, and the ${in the middle of the double quotation mark can be parsed into an expression run.

(4) List and map types

The list implementation is the Java java.util.ArrayList, the variables are surrounded by [], separated by commas, such as

 
 

The implementation of the map is Java.util.LinkedHashMap, also surrounded by [], separated by commas, where the key value pairs are key:value forms, such as:

def colors = [red: ' #FF0000 ', Green: ' #00FF00 ', Blue: ' #0000FF ']   
 
assert colors[' red ' = = ' #FF0000 '//value can be [key] or. Key shape Type 
assert colors.green = ' #00FF00 '  

(5) Closure (Closures)

Closures I understand like function pointers in C, or function objects that can be called like functions
{[Closureparameters->] Statements}
Example

def testclosure = {int arg1, String arg2->//def can be omitted, parameters can be omitted, default has it, when only-> represents no parameters 
 println "arg2:${arg2}"//Executed code, The return value is the last sentence, which can also be invoked with the returns 
} 
 
: 
testclosure (1, ' 2 ') 
Testclosure.call (1, ' 2 ') 

3.Gradle

Then there is the automation tool, the programming language, that implements a series of specific processes to generate APK, and see how it is implemented. Project in Gradle, which represents a project to be compiled and packaged, can generate apk that can contain more than one project in Jar,project, and each project consists of a number of tasks that can be understood as a different process Each task has a different action, and a series of actions to be performed (or the statement you are writing to execute). The order in which tasks are executed in project is controlled by their dependson.
The lifecycle of Gradle execution is performed as a task and is performed on the command line with a gradle task, which is divided into three phases (the build lifecycle is described in detail in the official use manual):

(1) Initialization phase

To determine which projects are included, create a corresponding project instance, and see the most recent execution of the statements in Settings.gradle

(2) Configuration stage

Create different tasks (tasks can be generated dynamically) and determine the order in which tasks are executed, or disable certain tasks, based on the dependson between tasks. When this phase is complete, the dependencies between tasks are determined.

(3) Implementation phase

After the configuration is complete, follow the dependencies and execute sequentially.

Note that statements that are typically in a task are executed at the configuration stage, and dofirst,dolast such action is in the execution phase. So there's a problem where the statement in the task that is not in your dependencies is executed.

As the following example, the printed task contents are not the same

Task Printtasksname { 
 Tasks.all {//all is a method in which arguments can be closures, and the parentheses of functions can be omitted 
 println "Show tasks in Configuration:${it.name } "//it is the default parameter for closures 
 } 
 dofirst { 
 tasks.all { 
 println" Show tasks in Execution:${it.name} " 
 } 
 } 
} 

4.Gradle Plugins and Androd Plug-ins
After providing basic process control, the next step is what to do and what to build. Gradle provides language-specific plug-ins such as Java,groovy, which is responsible for compiling, integrating plug-ins such as Application,war to generate Java executables, web program war files. Android has written its own plug-ins based on the process generated by APK, which also uses Java Plug-ins.

(1) The plug-in name of the custom plug-in is Resources/meta-inf/gradle-plugins

In the Resources/meta-inf/gradle-plugins directory has a suffix of the properties file, the name of the file is your build.gradle in the use of Plug-ins, which declared the implementation of the plug-in class. There are two plug-in names in Android.properties and com.android.application.properties in the source code of the Android plug-in, so in Build.gradle, application engineering uses the Android plug-in to apply Plugin: ' Android ' (already deprecated) or Apply plugin: ' Com.android.application '

(2) The application implementation class in the Android plug-in is Appplugin, inherits from the Com.android.build.gradle.BasePlugin, invokes the Apply method, the corresponding Configureproject (), Parse local.properties, Get SDK location, create Androidbuilder, apply Javabaseplugin, then Createextension () associate Buildtype,productflavor, Signingconfig, finally Createtasks (), complete the creation of each task

5.DSL (Domain specific Language)

DSL I translate into a domain-specific language, where the rules are set out in advance, or jargon. A common type in a Gradle DSL, a type that has project, task, and so on, defines different actions and usages for them, one is the statement block (the build script blocks or the configuration Block), such as Buildscript {},allprojects {}, common in Build.gradle. Android also defines a very multiple statement block, such as Buildtypes {},sourcesets {}.

Android Gradle Plug-in Configuration

With the above concept, and then look at the android application of the Build.gradle, in fact, the text can only say some, but more can see their own Android plug-in DSL

Apply plugin: ' com.android.application '//using Android plugin, non-Library project, generated is apk dependencies {compile ' Com.android.support:mult idex:1.0.1 ' Compile Filetree (dir: ' Libs ', include: ' *.jar ') Compile project (': Library Engineering 1 ')//code, resources included in the main program APK PR Oject (': Library project 1 ')//only participate in compiling, not output to target apk in}//Android plug-in DSL appextension type Android {compilesdkversion rootProject.ext.co Mpilesdkversion//Multi-project configuration uniform Properties Buildtoolsversion rootProject.ext.buildToolsVersion//lint check to avoid lint detect not eligible exit compile Li  ntoptions {Abortonerror false}//Gradle the default merge library project manifest to the main project, if the main program and library project package name inconsistency will be problematic enforceuniquepackagename = False//All product flavors inherits Defaultconfig {ApplicationID "Cn.arainfo" minsdkversion targetsdkversion 1 0//multidexenabled true dexoptions {javamaxheapsize "2g" Jumbomode True}}//Here because the project is imported from eclipse, all paths are made a declaration sourcesets {main {manifest.srcfile ' androidmanifest.xml ' java.srcdirs = [' src '] resources.srcdirs = [' sr C '] Aidl.srcdirs = [' sRC '] renderscript.srcdirs = [' src '] res.srcdirs = [' res '] assets.srcdirs = [' Assets ']} debug.setroot (' Build-t 
 Ypes/debug ') release.setroot (' Build-types/release ')}//compilation type, specifying release's Proguard profile Buildtypes {release { minifyenabled true Proguardfile ' Proguard.flags '}} afterevaluate {println ' afterevaluate set Projec T DependsOn ... "project (': Main program Engineering '). Tasks.getbyname (" Assembledebug "). DependsOn": Subroutine Engineering: Assembledebug "if (project.ha Sproperty (' testrelease ')) {Project (': Main program Project '). Tasks.getbyname ("Assemblerelease"). DependsOn ": Subroutine Engineering: 
 Assemblerelease "}}

Description of several places

(1) If you declare a common property in the build.gradle of the root directory

ext {
 Compilesdkversion =
 buildtoolsversion = ' 25.0.0 '
 isonwindows = os.isfamily (os.family_windows)
}

(2) buildtypes {},productflavors{},signingconfigs {}

The above three statement blocks, the type is Nameddomainobjectcontainer<t>, where T is BuildType productflavor signingconfig, and buildtypes {}, Add a new type to the productflavors{}, it will generate a new task, the rule is assemble[flavor][buildtype], so when the compilesdkversion is lower and the multidex is used, Also want to use Instantrun, you can create a new buildtype, only use when testing

(3) afterevaluate statement block

Android's Gradle plug-in version when 2.2.0, task creation is already afterevaluate, so if you want to continue using Tasks.getbyname ("Assembledebug"), You must write your own statement to the afterevaluate {} statement block

Summarize:

More write more guilty, fragmented content is very much, according to their own understanding through down, covering part of the content, basic can understand build.gradle. But there is no good understanding of how statement blocks such as Buildtypes {} and BuildType are associated (or how to parse them out and create objects).
If you have time to take a good look at the "in-depth understanding of Android (a): Gradle detailed," The general problem, such as multi-channel packaging productflavors How to configure Ah, by checking the Android DSL can be solved.

Reference Documentation:

1.Groovy Official Document
2.Gradle User Manual
DSL for 3.Gradle
DSL for 4.Android plugins
5. In-depth understanding of Android (i): Gradle detailed

Thank you for reading, I hope to help you, thank you for your support for this site!

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.