Use Gradle to build an Android Project

Source: Internet
Author: User

The new project uses a new tool released by Google I/O 2013, uses Gradle to build an android project, and supports it in the new Intellig IDEA and google Android Studio. This article describes how to use gradle to build an android project and compile multiple versions.

What is Gradle?

Gradle is an automated build tool based on Groovy, java applications, and DSL syntax. Is a new tool introduced by google to replace ant and maven. It depends on maven and ivy.
Purpose of using gradle:

    It is easier to reuse resources and code;

    It is easier to create different versions of programs and multiple types of apk packages;

    Easier configuration and expansion;

    Better IDE integration;

    Environment requirements

    Gradle1.10 or later, grale plug-in 0.9 or later.
    Android SDK requires Build Tools 19.0.0 and later.

    Gradle Basic Structure

    A project built using gradle created by ide automatically creates a build. gradle, as shown below:

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

    As you can see, the Build File mainly has three areas:

    Buildscript {...}

    Configures the build script classpath for this project. Set the script running environment

    Apply plugin: 'android'

    Set up to build a project using the android plug-in

    Android {...}

    Set parameters for compiling android Projects

    Task execution

    There are usually the following tasks:

      Assemble The task to assemble the output (s) of the project (output a project file, android is to package apk)

      Check The task to run all the checks. (run The check, check program errors, syntax, and so on)

      Build This task does both assemble and check (execute assemble and check)

      Clean This task cleans the output of the project (clear the project output file)

      The above tasks include assemble, check, and build. They are actually collections of other tasks.

      The method for executing a task isGradle Task Name, Suchgradle assemble

      In the android project, there is connectedCheck (check the connected device or simulator) and deviceCheck (check the api version used by the device)

      Generally, our project generates at least two versions, debug and release. We can use two tasks, assembleDebug and assumerelease, to generate two versions respectively. We can also use assemble to generate two versions at once.

      Gradle supports the abbreviated Task Name.Gradle assumereleaseYou can useGradle aR.

      Basic build Customization

      You can configure the program version and other information in the build. gradle file to generate programs of multiple versions.
      The following configurations are supported:

        Minimum sdk version supported by minSdkVersion

        Target sdk version during targetSdkVersion Compilation

        VersionCode program version

        VersionName program version name

        PackageName package name

        Package Name for the test application Package Name for testing

        An example of Instrumentation used for the test runner test.

        For example:

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

        By default, the project directory is like this.
        There are two components, source sets, one main and one test, which correspond to the following two folders.
        Src/main/
        Src/androidTest/

        Each component directory has two directories, respectively storing java code and resource files.
        Java/
        Resources/

        For android projects, the corresponding directories and files are
        AndroidManifest. xml // This file is not required in the src/androidTest/directory. It is automatically constructed during program execution.
        Res/
        Assets/
        Aidl/
        Rs/
        Jni/

        If you need these files but not the directories mentioned above, you need to set them.

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

        You can set the root directory for main or test, as shown in figure

         sourceSets {        androidTest.setRoot('tests')    }

        You can specify the storage path for each file.

        sourceSets {        main {            manifest.srcFile 'AndroidManifest.xml'            java.srcDirs = ['src']            resources.srcDirs = ['src']            aidl.srcDirs = ['src']            renderscript.srcDirs = ['src']            res.srcDirs = ['res']            assets.srcDirs = ['assets']        }    }

        In particular, the. so file generated by our ndk is usually not stored in the jni directory. We need to set it.

        sourceSets {        main {            jniLibs.srcDirs = ['libs']        }    }
        Signature Configuration

        You can perform different configurations for different types. First, let's look at the example:

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

        The Configuration File above is configured with two types: one debug type and the other custom type. The two use different signatures respectively, and you must enter the set password for generating the key.

        Code obfuscation settings

        View the Code directly:

        android {    buildTypes {        release {            runProguard true            proguardFile getDefaultProguardFile('proguard-android.txt')        }    }}

        The above uses the default proguard file for obfuscation, or you can use your own coding rules for obfuscation,proguardFile 'some-other-rules.txt'

        Dependency Configuration

        The program will depend on other packages or programs, and other class libraries need to be introduced. As mentioned above, maven is supported.
        For local class libraries, you can introduce them as follows:

        Dependencies {compile files ('libs/foo. jar ') // compile fileTree (dir: 'libs', include :['*. jar ']) // multiple files} android {...}

        For maven repository files:

        repositories {    mavenCentral()}dependencies {    compile 'com.google.guava:guava:11.0.2'}android {    ...}
        Output applications with different configurations

        Check the Code:

        android {    ...    defaultConfig {        minSdkVersion 8        versionCode 10    }    productFlavors {        flavor1 {            packageName "com.example.flavor1"            versionCode 20        }        flavor2 {            packageName "com.example.flavor2"            minSdkVersion 14        }    }}

        With the above settings, we can output different versions with different life-saving versions and the minimum sdk package. Of course, we can make other differences based on our own needs.

        Generate multiple channel packages (using Umeng as an example)

        My complete configuration file

        Buildscript {repositories {mavenCentral ()} dependencies {classpath 'com. android. tools. build: gradle: 0.9. + '} apply plugin: 'android' repositories {mavenCentral ()} android {compileSdkVersion 19 buildToolsVersion "19.0.3" defaultConfig {minSdkVersion 8 targetSdkVersion 19 versionCode 1 versionName "1.0"} sourceSets {main {jniLibs. srcDirs = ['libs']} lintOptions {abortOnError false} // signature signingConfigs {// your own keystore Information release {storeFile file ("x. keystore ") storePassword" ××× "keyAlias" ×××× "keyPassword" ××× "} buildTypes {debug {signingConfig signingConfigs. release} release {signingConfig signingConfigs. release runProguard false proguardFiles getdefadefaproguardfile('proguard-android.txt '), 'proguard-rules.txt'} // channel Flavors. I have written some frequently used, change productFlavors {// GooglePlay {} // Store360 {} // QQ {} // Taobao {} // WanDouJia {} // AnZhuo {} // AnZhi {} // BaiDu {} // Store163 {} // GFeng {} // AppChina {} // EoeMarket {} // Store91 {} // NDuo {} xiaomi {} umeng {}}}// replace AndroidManifest. the xml UMENG_CHANNEL_VALUE string is the channel name android. applicationVariants. all {variant-> variant. processManifest. doLast {// copy {} previously used here. I changed it to a file operation, which can run normally in v1.11 and keep the folder clean. // $ {buildDir} indicates. /build folder // $ {variant. dirName} is flavor/buildtype, for example, GooglePlay/release. The following path is automatically generated during runtime :. /build/manifests/GooglePlay/release/AndroidManifest. xml def manifestFile = "$ {buildDir}/manifests/$ {variant. dirName}/AndroidManifest. xml "// Replace the string UMENG_CHANNEL_VALUE with the flavor name def updatedContent = new File (manifestFile ). getText ('utf-8 '). replaceAll ("UMENG_CHANNEL_VALUE", "$ {variant. productFlavors [0]. name} ") new File (manifestFile ). write (updatedContent, 'utf-8') // set the AndroidManifest of flavor. the xml file is specified as the modified file variant. processResources. manifestFile = file ("$ {buildDir}/manifests/$ {variant. dirName}/AndroidManifest. xml ")}}

        The above function is to replace the umeng channel ID in my Manifest and generate different apk packages.

        Final description

        During the buid process, the program executes the lint check. Any errors or warnings will terminate the build and we can disable it.

        lintOptions {        abortOnError false    }
        Last PS

        My use of gradle is indeed much more convenient, although the computer configuration is low, build is slow.
        For details, refer to the official Google documentation.
        About how to install, not mentioned, can refer to this article: http://stormzhang.github.io/android/2014/02/28/android-gradle/

        I have attached my reference documents. If you do not understand them, you can check them out. Http://tools.android.com/tech-docs/new-build-system/user-guide

        Original article address: Workshop.

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.