Android Gradle plug-in user guide, androidgradle

Source: Internet
Author: User

Android Gradle plug-in user guide, androidgradle
Android Gradle Plug-In User Guide)

Original article Gradle Plugin User Guide-Android Tools Project Site
Samples see bottom of New Build System
Refer to Gradle For Android Training Course

1 Overview

This document is based on the Gradle plug-in of version 0.9. Versions earlier than 1.0 may be different due to incompatibility.

1.1 New system construction goals

The goal of the new system is:

  • Makes code and resource reuse easier.
  • It makes it easier to create different versions of the same application, whether multiple apk versions or multiple customization of the same version
  • Makes configuration, extension, and custom building easier
  • Good IDE Integration
1.2 Why Gradle

Gradle is an advanced build system and build tool that allows you to customize build logic through plug-ins

The following features enable Gradle:

  • Use a specific domain language (DSL) to describe and control the building Logic
  • The build script is based on the Groovy language and allows the DSL Mixed Element Declaration and the DSL element control through code to generate custom build logic.
  • Support Maven and (or) Ivy dependency management
  • Flexible. Allow use of best practices, but do not force your own implementation
  • The plug-in can provide its own DSL and API for use by build scripts.
  • Provides excellent tool APIs for IDE Integration
2. environment requirements
  • Gradle 1.10, 1.11, or 1.12, and plug-in version 0.11.1
  • SDK and Buid Tools 19.0.0, some features may need to be updated
3. Basic Projects

The Gradle project describes the build process through the build. gradle file in the project root directory.

3.1 simple file Construction

The simplest Java Project build File build. gradle

apply plugin: 'java'

This script applies the Java Plug-in of Gradle. This plug-in provides all the functions for building and testing Java applications.

The build file of the simplest Android project contains the following content:

buildscript {    repositories {        mavenCentral()    }    dependencies {        classpath 'com.android.tools.build:gradle:0.11.1'    }}apply plugin: 'android'android {    compileSdkVersion 19    buildToolsVersion "19.0.0"}    

Note ):Latest android plug-in Declaration
apply plugin: 'com.android.application'

The Android build script contains three main contents:

buildscript { ... }The code that drives the build process is configured. In this case, the Maven repository and the dependent path of a Maven file (artifact) are declared. This file contains the library of the Android Gradle plug-in. The version is 0.11.1.

Then,androidThe plug-in is applied, just like the previous Java Plug-in.

Finally,android { ... }Parameters required for anroid building are configured. This is also the entrance of Adnroid DSL. By default, only the target SDK version is compiled and the build tool version is required. In the script, the correspondingcompileSdkVersionAndbuildtoolsVersionAttribute.compileSdkVersionIn the old compilation systemproject.propertiesFiletargetAttribute. This new propertycompileSdkVersionIt can be an int value (API Level) or a sumtargetString with the same attribute value

Important:You should only apply the android plug-in and apply the java Plug-in to cause a build error.

Note:You also needlocal.propertiesFile to specify the SDK path, andbuild.gradleIn the same path, usesdk.dirAttribute. Or, you can setANDROID_HOMEEnvironment variable. The two are the same. You can choose one method you like.

3.2 project structure

The previous android build script uses the default folder directory structure. Gradle followsConvention is better than ConfigurationWhen possible, a reasonable default configuration parameter is provided.

The basic project contains two "source sets" components.main source codeAndtest codeIn the following directory:

src/main/src/androidTest/

In these directories, the source code components of the directories exist.

Both the Java and Android plug-ins, the source code directory and the Resource Directory are as follows:

java/resources/

For Android plug-ins, there are also unique files and directories

AndroidManifest.xmlres/assets/aidl/rs/jni/

Note: src/androidTest/AndroidManifest.xmlIt is not mandatory and will be automatically created.

3.2.1 configure the project structure

When the default project structure is not suitable, you can configure the project directory. According to the Gradle document, you can use the following script to reconfigure the sourceSets of the Java project:

sourceSets {    main {        java {            srcDir 'src/java'        }        resources {            srcDir 'src/resources'        }    }}

Note:SrcDir adds the specified directory to the source file directory list (this is not mentioned in the Gradele document, but it is actually like this ).

To replace the default source file directory list, you can usesrcDirsTo specify the directory array. This is also a different method of use:

sourceSets {    main.java.srcDirs = ['src/java']    main.resources.srcDirs = ['src/resources']}

For more information, see the Java Plug-in content in the Gradle document.

Android plug-ins use similar syntaxes, but they use their ownsourceSets, The corresponding directory is in (build.gradleFile) specified in the android object

The following is an example. It uses the source code structure of the old project and maps androidTest sourceSet to the tests directory.

android {    sourceSets {        main {            manifest.srcFile 'AndroidManifest.xml'            java.srcDirs = ['src']            resources.srcDirs = ['src']            aidl.srcDirs = ['src']            renderscript.srcDirs = ['src']            res.srcDirs = ['res']            assets.srcDirs = ['assets']        }        androidTest.setRoot('tests')    }}

Note:Since the old structure puts all source files (java, aidl, renderscript, and java resource files) in one directory, We need to map these sourceSet components to the src directory.

Note:The setRoot () method directs the entire sourceSet (including sub-Directories) to a new directory. For examplesrc/androidTest/*Pointedtests/*

The above is unique to Android and does not work if it is configured in Java sourceSets.

The 'migrated 'example (located at the bottom of this page) shows this part of content.

3.3 build task 3.3.1 General task

Applying a plug-in the build file will automatically create a series of build tasks. Both Java Plug-ins and Android plug-ins are like this. The task conventions are as follows:

  • Assemble

Combined project output

  • Check

Perform all checks

  • Build

Execute all tasks assemble and check.

  • Clean

Clear Project output

Taskassemble,checkAndbuildWill not do anything practical. They are just anchor tasks, and the plug-ins rely on them to add the tasks that actually perform the operations.

In this way, you do not need to consider what type of project and what plug-ins are used, and you can execute the same task.
For example, if you use the findbugs plug-in, a new task is created andcheckDepending on this taskcheckThis task will be called when it is called.

Run the following tasks in the terminal (command line, gradle project directory) to query high-level tasks:

gradle tasks

Run the following command to view the dependencies between all tasks and tasks:

gradle tasks --all

Note:Gradle automatically monitors input and output files declared by a task. If the file does not change when you execute the build task again, Gradle indicates that all tasks areUP-TO-DATEThis means that the task does not need to be executed. In this way, tasks can correctly depend on each other without leading to non-essential build operations.

3.3.2 Java Project Task

The Java Plug-in mainly creates two tasks. The dependency between these two anchor tasks is as follows:

  • Assemble
    • Jar
      This task creates an output
  • Check
    • Test
      This task runs the test

jarTasks depend on other tasks directly or indirectly: for exampleclassesThe task will compile the Java source code
testClassesThe task is used for compiling and testing, but this task is rarely called becausetestTask depends on it (just like dependencyclassesSame task)

Generally, you only need to callassembleOrcheckTask without calling other tasks.

You can see all the tasks and descriptions of the Java Plug-in the Gradle Java Plug-in documentation.

3.3.3 Android task

The Android plug-in uses the same conventions to maintain compatibility with other plug-ins and adds additional anchor tasks:

  • Assemble
    Output of the task organization project

  • Check
    This project runs all checks

  • ConnectedCheck
    The running check requires a connected device or simulator. And runs asynchronously on all connected devices.

  • DeviceCheck
    Connect to the remote device through APIs and run the check. This usually runs on the CI server.

  • Build
    RunassembleAndcheck

  • Clean
    Clear Project output

A new anchor task is required to ensure that you can run regular checks without requiring device connection.
Note that,buildTask is not dependentdeviceCheckOrconnectedCheck

An Android project has at least two outputs: debug APK and release APK. Each of them has its own anchor tasks to help them build independently:

  • Assemble
    • AssembleDebug
    • Assumerelease

They all rely on other tasks to complete the multiple steps required to build an apk.assembleThe task depends on the two tasks, so the callassembleTwo APK files are generated.

Tip: Gradle supports the abbreviated job name in the form of camel in the command line.
For example:
gradle aRAndgradle assembleReleaseIs the same, because no other task name has the same abbreviation

Anchor taskcheckIt also has its own dependencies:

  • Check
    • Lint
  • ConnectedCheck
    • ConnectedAndroidTest
    • ConnectedUiAutomatorTest (not implemented yet)
  • DeviceCheck
    • Depends on the tasks created when other plug-ins implement the test extension.

Finally, the plug-in will be created for all build types (debug, release, test)install/uninstallTask, if the output file can be installed (must be signed ).

3.4 basic build process Customization

The Android plug-in provides a large number of DSL to customize most things directly from the build system.

3.4.1 Manifest attributes

With DSL, you can configure the following manifest attributes:

  • MinSdkVersion
  • TargetSdkVersion
  • VersionCode
  • VersionName
  • ApplicationId (actual packageName-go to ApplicationId versus PackageName to view more)
  • Package Name for the test application
  • Instrumentation test runner

For example:

android {    compileSdkVersion 19    buildToolsVersion "19.0.0"    defaultConfig {        versionCode 12        versionName "2.0"        minSdkVersion 16        targetSdkVersion 16    }}

The configuration item is located inandroidElementdefaultConfigElement.

In earlier versions, Android Plugin uses packageName to configurepackageNameAttribute. Starting from version 0.11.1, you should use applicationId In the build. gradle file to configurepackageNameAttribute.
This is to eliminate Android applicationspackageName(As the Android app ID) and java package name.

What's powerful in the build file is that it can be dynamic.
For example, you can read the version name from a file or use custom logic:

def computeVersionName() {    ...}android {    compileSdkVersion 19    buildToolsVersion "19.0.0"    defaultConfig {        versionCode 12        versionName computeVersionName()        minSdkVersion 16        targetSdkVersion 16    }}

Note:The function name must not conflict with the existing getter method name in the specified range. For exampledefaultConfig { ...}The call to getVersionName () will automatically use defaultConfig. getVersionName () instead of other custom getVersionName ().

If the property is not set through DSL, the default property value will be used. The default attribute values are listed below:

Property Name Default value in DSL object Default value
VersionCode -1 Value from manifest if present
VersionName Null Value from manifest if present
MinSdkVersion -1 Value from manifest if present
TargetSdkVersion -1 Value from manifest if present
ApplicationId Null Value from manifest if present
TestApplicationId Null ApplicationId + ". test"
TestInstrumentationRunner Null Android. test. InstrumentationTestRunner
SigningConfig Null Null
ProguardFile N/A (set only) N/A (set only)
ProguardFiles N/A (set only) N/A (set only)

If you read these attributes using custom logic in the build script, the attributes in the second column are very important. For example, you may write:

if (android.defaultConfig.testInstrumentationRunner == null) {    // assign a better default...}

If this value is null, it will be replaced by the default value of the third column during the construction process, but the DSL element does not contain this default value (the value of the third column), so you cannot query this value. This is to prevent parsing the manifest file of the application unless necessary.

3.4.2 Build type (Build Types)

By default, the Android plug-in automatically sets the project to build both debug and release applications.
The major difference between the two versions is whether the program can be debugged on a security device and how the APK is signed.

The debug version uses an automatically created key/certificate and a known name/password for signature (to prevent request prompts during the build process ). The release version does not have a signature during the build process and needs to be signed later.

These configurations are set through a build type (BuildTpye) object. By default, both the debug and release build types are created.

The Android plug-in allows you to customize the two instances and create other build types. These are all configured in the DSL container of buildTypes:

android {    buildTypes {        debug {            applicationIdSuffix ".debug"        }        jnidebug.initWith(buildTypes.debug)        jnidebug {            packageNameSuffix ".jnidebug"            jniDebuggable true        }    }}

The preceding code snippets provide the following functions:

  • Configure the defaultdebugBuild type:

    • Set the package name<app appliationId>.debugTo install both debug and release versions on the same device.
  • A new name is createdjnidebugIs a copy of the debug build type.

  • ConfigurationjnidebugBuild type, allows debugging of JNI components, and adds a different package name suffix

Create a new build type, as shown inbuildTypesUsing a new element in a container is as simple as callinginitWith()Or use closures to configure

The following are the attributes that may be used and their default values:

Property name Default values for debug Default values for release/other
Debuggable True False
JniDebuggable False False
RenderscriptDebuggable False False
RenderscriptOptimLevel 3 3
ApplicationIdSuffix Null Null
VersionNameSuffix Null Null
SigningConfig Android. signingConfigs. debug Null
ZipAlignEnabled False True
MinifyEnabled False False
ProguardFile N/A (set only) N/A (set only)
ProguardFiles N/A (set only) N/A (set only)

In addition to the preceding attributes,Build TypesThe build process can also be affected by source code and resources.
Each build type creates a matchedSourceSet, The default path is:

src/<buildtypename>/

This means that the name of the new build type cannot beMainOrAndroidTest(This is mandatory for the plug-in), and the name of the build type must be unique.

Like othersSourceSetSameSourceSetCan be redirected again:

android {    sourceSets.jnidebug.setRoot('foo/jnidebug')}

In additionBuild TypeAassemble<BuildTypeName>Task.

Before,assembleDebugAndassembleReleaseAs mentioned above, this is their source. When the debug and release build types are pre-created, their related tasks are automatically created, suchassembleDebugAndassembleRelease

The aboveBuild. gradleThe clip will also be createdassembleJnidebugTask,assembleWill be similar to dependencyassembleDebugAndassembleReleaseSame task dependencyassembleJnidebug.

Tip: You can entergradle aJTo runassembleJnidebugTask.

Possible scenarios:

  • Permissions are required only in debug mode, but not in release mode.
  • Custom debug implementation
  • Debug mode uses different resources (for example, the resource value is bound to the signature certificate)

BuildTypeThe source code and resources are used in the following ways:

  • Merge the manifest file into the manifest file of the app.
  • Source code as another source code directory
  • Overlay the resource to the main resource to replace the existing value.
3.4.3 signature configuration

The following is required to sign an application:

  • One keystore
  • One keystore Password
  • Alias of a key
  • One key password
  • Storage Type

Location, alias, two passwords and one storage type constitute a signature configuration (SigningConfig)

By default,debugThe signature configuration uses a debug keystore, known passwords, known aliases, and alias passwords.
Debug keystore is located$HOME/.android/debug.keystoreIf not, one is automatically created.

debugThe build type is automatically used.debug SigningConfig.

You can create other signature configurations or customize the default built-in configurations. PasssigningConfigsDSL container to configure

android {    signingConfigs {        debug {            storeFile file("debug.keystore")        }        myConfig {            storeFile file("other.keystore")            storePassword "android"            keyAlias "androiddebugkey"            keyPassword "android"        }    }    buildTypes {        foo {            debuggable true            jniDebuggable true            signingConfig signingConfigs.myConfig        }    }}

Modify the location of the debug keystore in the above snippet to the project root directory. This affects any build type that uses it. In this casedebugBuild type.

A new signature configuration and a build type of the row using the new signature configuration are also created here.

Note:It is automatically created only when the debug keystore does not exist in the default path. Changing the debug keystore path will not automatically create the debug keystore in the new path. Create a signature configuration with different names, but use the default debug keystore path, the debug keystore is automatically created. That is to say, whether to automatically create a debug keystore is determined by the location of the keystore, rather than the configured name.

Note:The keystore path is usually the relative path of the Project root directory, but you can also use the absolute path, although this is not recommended (except for debug keystore because it will be automatically created ).

** Note: If you want to add these files to the version control system, you may not want to write the password in the file. The following Stack Overflow Connection provides a method for reading from the console or environment variables.
Http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle
We will update the Guide in the future to provide more details **

3.4.4 run ProGuard

ProGuard is supported from Gradle plugin for ProGuard 4.10 (since Gradle plugin 0.4 ). IfminifyEnabledIf the property is set to true, the Progruard plug-in is automatically added and the corresponding task is automatically created.

Note:BuildType. runProguard is changed to minifyEnabled from Gradle plug-in version 0.14.0. For details, refer to Release notes

android {    buildTypes {        release {            minifyEnabled true            proguardFile getDefaultProguardFile('proguard-android.txt')        }    }    productFlavors {        flavor1 {        }        flavor2 {            proguardFile 'some-other-rules.txt'        }    }}

Variant uses all declared rule files, including those declared in the corresponding Build Type and flavor.

The SDK has two default rule files:

  • Proguard-android.txt
  • Proguard-android-optimize.txt

They are located in the sdk path, usingGetdefaproproguardfile ()You can obtain the complete path of the file. They are the same except for whether to optimize them.

3.4.5 compressing resource files

You can automatically Remove unused resource files during building. For more details, see file resource file compression.

4 dependency, Android library project and multi-Project Settings

The Gradle project can depend on other components. These components can be external Binary packages or other Gradle projects.

4.1 dependent on Binary Package 4.1.1 local package

To configure an external library jar dependency, you needcompileAdd a dependency in configuration

dependencies {    compile files('libs/foo.jar')}android {    ...}

Note: dependenciesDSL elements are part of the standard Gradle API and do not belongandroidElement.

compileThe configuration is used to compile the main application. Anything added to the compilation path will be packaged into the final apk file.
The following are some other configurations that may be used to add dependencies:

  • compile: Main module
  • androidTestCompile: Test module
  • debugCompile: Compilation of the debug build type
  • releaseCompile: Release build type Compilation

Because building an apk must have a related build type, the apk usually has at least two compilation configurations:compileAnd<buildtype>Compile
When a build type is created, a compilation configuration based on its name is automatically created.<buildtype>Compile

When you need to use a custom Library (such as recording crash information) in the debug version, but the release version is not required, or they depend on different versions of the same library, it is very useful.

You can also add a directory to depend on all jar files in the directory:
compile fileTree(dir: 'libs', include: ['*.jar'])

4.1.2 Remote File

Gradle supports obtaining dependent files from Maven Or Ivy repositories.

First, you must add the repository to the list. Second, you must declare the dependency according to the Maven Or Ivy file declaration specifications.

repositories {    mavenCentral()}dependencies {    compile 'com.google.guava:guava:11.0.2'}android {    ...}

Note: mavenCentral()Is a convenient way to specify the repository URL. Gradle supports remote and local warehouses.
Note:Gradle follows the dependency transmission. If a dependent file is dependent on other files, the dependent files will also be pulled down.

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.