Understanding using Gradle to build packaged Android APK

Source: Internet
Author: User

The purpose of this article: Understanding the Gradle construction process, interpreting the Android Gradle plug-in configuration read this article must be used Gradle to generate APK, the text will not talk about how to install the run Gradle, if necessary, you can read the article at the end of the reference.
APK package is a ZIP package, from Java source code, resource files to generate this apk, after the compilation of a series of specific procedures, this process can be viewed in the "use Ant packaged Android app--apk build Process", you can also from your own Legacy SDK documentation (/docs/ tools/building/index.html) found in the. This series of specific processes, repetitive and tedious, the build tool is to process these processes, freeing your hands. Ant as an early build tool for APK, the build process is very intuitive, like configuration, Gradle can be conveniently configured, but more like a script, can be programmed.
Understanding Gradle Construction1. Simple understanding of build toolsFrom a programmer's point of view, how do you write code to automate your APK build process? First of all, you need to know where the SDK, NDK where the Android project has several library projects, their Java source code, resource files, respectively? The command line input parameters certainly do not meet the requirements, it is natural to think of the configuration file. So your automation tool is to parse these configuration files according to the program required to generate the APK file. Gradle is such a tool program, the configuration file is your common settings.gradle,build.gradle, but he also provides more features, such as dependency management, Process control, and plug-in mechanism to customize your build process. Gradle's programming language is groovy, which requires a configuration file that supports groovy. The groovy language, like Java, is JVM-based and well-supported for Java, so you can write extensions in Java code, write configuration files like normal programming, instead of using XML to write configuration logic like Ant.2.GroovyGroovy's syntax, putting its own code in the thumbnail looks like a script, and I just looked at a little bit of documentation, listing our usual introductions: First groovy is an object-oriented dynamic language(1) A semicolon can be omitted at the end of a statement(2) variable definition can be used with def or directly(3) function definition can be used with def or not (with return value declaration can also)function can omit parameter typefunction calls can omit parenthesesLet's look at an example:
println ' Hello '                                 int power (int n) {2**n}                       println "2^6==${power (6)}"
The first line outputs the 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 typesThe list implementation is the Java java.util.ArrayList, the variables are surrounded by [], separated by commas, such as
def heterogeneous = [1, "A", true]//its elements can be any object

The implementation of MAP is Java.util.LinkedHashMap, also surrounded by [], separated by commas, where the key value pair is key:value form, such as:
def colors = [red: ' #FF0000 ', Green: ' #00FF00 ', Blue: ' #0000FF ']   
(5) Closure (Closures)Closures I understand like a function pointer in C, or a function object, an object that can be called like a function {[closureparameters] statements} example
def testclosure = {int arg1, String arg2->//def can be omitted, parameters can be omitted, default is it, when only---no parameter println "ARG2:${ARG2}"//Executed code, The return value is the last sentence or can be called with return}: Testclosure (1, ' 2 ') Testclosure.call (1, ' 2 ')

3.GradleThen there is the automation tool, the programming language has, the implementation of a series of specific processes to generate the APK, see how to implement. There is project in Gradle, which represents a project to be compiled for packaging, can generate APK, can build Jar,project can contain multiple projects, each project is composed of many tasks, can be understood as a different process Each task has a different action, and a series of actions to be performed (or statements that you write to execute). The order in which task is executed in project is controlled by its dependson. The Gradle execution is performed as a task, executed at the command line as a gradle task, and the lifecycle of the process is divided into three phases (the Build Lifecycle is also described in the official user manual):(1) Initialization phaseDecide which projects to include, create the corresponding project instances, and see the most recent statements that were executed in Settings.gradle(2) configuration phaseCreate different tasks (tasks can be dynamically generated) and determine the order in which tasks are executed, depending on the dependson between tasks, or disable certain tasks. When this phase is complete, the dependencies between the tasks are determined.(3) Implementation phaseAfter the configuration is complete, follow the dependencies and execute sequentially. It is important to note that the statements that are normally in the task are executed during the configuration phase, while the Dofirst,dolast action is in the execution phase. So there's a problem with the statement in the task that you don't have in your dependency. The following example shows that the task content printed is not the same
Task Printtasksname {  Tasks.all {//all is a method, the argument can be a closure, and the function's meta-parentheses 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 pluginsAfter providing basic process control, the next step is what to do and what to build. Gradle provides for language-based plugins such as Java,groovy, which are responsible for compiling, integrated plug-ins such as Application,war and other generated Java executables, web program war files. Android, based on the process of apk generation, wrote its own plugin, which also uses the Java plugin. (1) The plugin name of the custom plug-in is suffixed with the properties file in Resources/meta-inf/gradle-plugins in the Resources/meta-inf/gradle-plugins directory, The name of the file is that you use the plug-in in Build.gradle, which declares the implementation class of the plugin. In the Android plug-in source can see the android.properties and com.android.application.properties two plug-in name, so in Build.gradle, application engineering using Android plugin need to apply Plugin: ' Android ' (already deprecated) or Apply plugin: ' Com.android.application ' (2) the application implementation class in the Android plugin is Appplugin, Inherit from Com.android.build.gradle.BasePlugin, call the Apply method, the corresponding Configureproject (), Parse Local.properties, get the SDK location, create Androidbuilder, apply Javabaseplugin, and then Createextension () associate Buildtype,productflavor, Signingconfig, Last Createtasks (), complete the creation of each task
5.DSL (Domain specific Language)The DSL I translate into a domain-specific language is a pre-defined rule here, or jargon. Common types in Gradle DSLs are types (type) that have project, task, and so on that define different actions and usages, one is a statement block (the build script block or the configuration Block) Buildscript {},allprojects {}, as common in Build.gradle. Very many statement blocks, such as Buildtypes {},sourcesets {}, are also defined in Android.
Android Gradle plug-in configuration with the above concept, and then look at the android application of Build.gradle, in fact, the text can only speak a few, but more can see their own Android plugin DSL
Apply plugin: ' com.android.application '//using Android plugin, non-Library project, generated is apkdependencies {compile ' com.android.support: multidex:1.0.1 ' Compile Filetree (dir: ' Libs ', include: ' *.jar ') Compile project (': Library project 1 ')//code, resources included in the main program APK provided p Roject (': Library project 1 ')//only participates in compiling, not output to target apk in}//Android plugin DSL appextension type Android {compilesdkversion RootProject.ext.compileSdkVersion//Multi-project configuration Unified Properties Buildtoolsversion rootProject.ext.buildToolsVersion//Lint check, Avoid lint detect non-compliant exit compilation Lintoptions {Abortonerror false}//Gradle compile will default merge library project manifest to main project, if the main program and library project package name inconsistency will be problematic Enforceuni Quepackagename = false//All product flavors inherit defaultconfig {ApplicationID "Cn.arainfo" minsdkversion Version 10//multidexenabled true dexoptions {javamaxheapsize "2g" Jumbomode True}}//Here because the project was imported from eclipse, all paths are Declaration Sourcesets {main {manifest.srcfile ' androidmanifest.xml ' java.srcdirs = [' src '] resources.srcdirs = [' src '] aid L.srcdirs = [' src '] renderscript.srcdirs = [' src '] res.srcdirs = ['Res '] Assets.srcdirs = [' Assets ']} debug.setroot (' Build-types/debug ') release.setroot (' Build-types/release ')}//Series  Proguard configuration file for release Buildtypes {release {minifyenabled true proguardfile ' proguard.flags '}}}afterevaluate {println "Afterevaluate set Project DependsOn ..." Project (': Main program Project '). Tasks.getbyname ("Assembledebug"). DependsOn ": Subroutine Engineering: Assembledebug "if (Project.hasproperty (' testrelease ')) {Project (': Main program Project '). Tasks.getbyname (" Assemblerelease " ). DependsOn ": Sub Program Project: Assemblerelease"}}

Description of several places(1) If public properties are declared in the build.gradle of the root directoryext {compilesdkversion = Buildtoolsversion = ' 25.0.0 ' isonwindows = os.isfamily (os.family_windows)}(2) buildtypes {},productflavors{},signingconfigs {}The above three block of statements, the type is Nameddomainobjectcontainer<t&gt, where T is BuildType productflavor signingconfig, and buildtypes {}, A new type is added to productflavors{}, and the rule is assemble[flavor][buildtype], so when compilesdkversion is low and multidex is used, the new task is generated. Also want to use Instantrun, you can create a new buildtype, only used in testing
(3) afterevaluate statement blockWhen the Android Gradle plugin version is 2.2.0, task creation is already in afterevaluate, so if you want to continue using Tasks.getbyname ("Assembledebug"), You must write your own statement into the afterevaluate {} statement block
Summary: The more written the more guilty, fragmented content is very much, according to their own understanding through, covering a part of the content, the basic can understand build.gradle. However, it is not well understood how the statement blocks, such as Buildtypes {} and BuildType, relate (or how to parse and create objects). If there is time to take a good look at the "deep understanding of Android (a): Gradle detailed", general questions, such as multi-channel packaging productflavors How to configure Ah, their own through the Android DSL can be solved.

Reference Documentation: 1. Groovy Official Documentation 2.Gradle user manual 3.Gradle dsl4.android plugin for DSL5. In-depth understanding of Android (i): Gradle detailed

Understanding using Gradle to build packaged Android APK

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.