Gradle Plugin for Android Development User Guide (1)

Gradle Plugin for Android Development User Guide (1)html

終於有點時間能夠學學一直打算了解的Gradle,畢竟打算之後在移動開發這條路上走到黑的話就要與時俱進,首先天然得用Google推薦的Android Studio,就目前來看,它除了還未徹底支持NDK以外,不少方面都是完爆Eclipse+ADT Plugin的,而新的構建系統Gradle更是不能不瞭解的內容,因而找了些有用的資料開始上手看。若是你通常都是進行常規的Android SDK的開發並且對Gradle沒啥興趣的話那麼直接看這篇官網教程就好了http://developer.android.com/sdk/installing/studio-build.htmljava

而本篇文章來自http://tools.android.com/Gradle Plugin User Guide我想應該是最好的讀物了,因而細細地通讀了一下,邊讀邊註解,注意不是翻譯,由於寶貴的時間有限並且原文並不難懂,因此只能是挑重要的內容註解一下,以便之後用到的時候可以更快的檢索到重要信息。android

文中標有[?]的地方表示我沒有理解,若有理解了的或者文中有任何錯誤煩請留言告知,不勝感激!git

原文地址:http://tools.android.com/tech-docs/new-build-system/user-guidegithub

由於註解完以後文章變得特別長,因此分紅2部分,第二部分地址:http://hujiaweibujidao.github.io/blog/2014/10/15/gradle-plugin-user-guide-2api

Introduction

This documentation is for the Gradle plugin version 0.9. Earlier versions may differ due to non-compatible we are introducing before 1.0.app

Goals of the new Build System

The goals of the new build system are:less

Make it easy to reuse code and resources
Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
Make it easy to configure, extend and customize the build process
Good IDE integrationmaven

Why Gradle?

Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.ide

Here are some of its features that made us choose Gradle:

Domain Specific Language (DSL) to describe and manipulate the build logic
Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
Built-in dependency management through Maven and/or Ivy.
Very flexible. Allows using best practices but doesn’t force its own way of doing things.
Plugins can expose their own DSL and their own API for build files to use.
Good Tooling API allowing IDE integration

[總結起來就是:DSL(Domain Specific Language ) + Groovy based Build files + Maven/Ivy based Dependency Management + Plugin Supported]

Requirements

Gradle 1.10 or 1.11 or 1.12 with the plugin 0.11.1
SDK with Build Tools 19.0.0. Some features may require a more recent version.

Basic Project

A Gradle project describes its build in a file called build.gradle located in the root folder of the project.

Simple build files

The most simple Java-only project has the following build.gradle:

apply plugin: 'java'

This applies the Java plugin, which is packaged with Gradle. The plugin provides everything to build and test Java applications.

The most simple Android project has the following build.gradle:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.11.1'
    }
}

apply plugin: 'android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"
}

There are 3 main areas to this Android build file:

(1) buildscript { ... } configures the code driving the build.
In this case, this declares that it uses the Maven Central repository, and that there is a classpath dependency on a Maven artifact. This artifact is the library that contains the Android plugin for Gradle in version 0.11.1

Note: This only affects the code running the build, not the project. The project itself needs to declare its own repositories and dependencies. This will be covered later.

[注意:這裏定義的repository和dependency只是build須要的,項目還須要定義本身的repository和dependency]

(2) Then, the android plugin is applied like the Java plugin earlier.

(3) Finally, android { ... }configures all the parameters for the android build. This is the entry point for the Android DSL.

By default, only the compilation target, and the version of the build-tools are needed. This is done with the compileSdkVersion and buildtoolsVersion properties.

[默認狀況下,只有編譯目標和編譯工具的版本號是必需要給定的。之前的build系統須要在項目的根目錄下的project.properties 文件中指定target (例如target=android-18),它對應的就是這裏的 compilation target,不過此處的值只是一個int值,表明Android API version]

The compilation target is the same as the target property in the project.properties file of the old build system. This new property can either be assigned a int (the api level) or a string with the same value as the previous target property.

Important: You should only apply the android plugin. Applying the java plugin as well will result in a build error.

[注意:這裏只能使用android插件,寫成java插件會出現build錯誤]

Note: You will also need a local.properties file to set the location of the SDK in the same way that the existing SDK requires, using the sdk.dir property.

Alternatively, you can set an environment variable called ANDROID_HOME. There is no differences between the two methods, you can use the one you prefer.

關於設置Android SDK的位置有兩種方式:

(1)在項目根目錄的local.properties 文件中指定sdk.dir 的值,若是包含ndk的話同時還要指定ndk.dir 的值

sdk.dir=/Volumes/hujiawei/Users/hujiawei/Android/android_sdk
ndk.dir=/Volumes/hujiawei/Users/hujiawei/Android/android_ndk

(2)在系統中設置環境變量ANDROID_HOME

Project Structure

The basic build files above expect a default folder structure. Gradle follows the concept of convention over configuration, providing sensible default option values when possible.

[Gradle遵循你們約定俗成的Android項目目錄結構和項目配置,一個基本的項目開始時包含了兩個源碼集合,即main source code和test source code,它們各自的源碼目錄下有分別包含了Java source code和Java resource]

The basic project starts with two components called 「source sets」. The main source code and the test code. These live respectively in:

src/main/
src/androidTest/

Inside each of these folders exists folder for each source components.
For both the Java and Android plugin, the location of the Java source code and the Java resources:

java/
resources/

For the Android plugin, extra files and folders specific to Android:

AndroidManifest.xml
res/
assets/
aidl/
rs/
jni/

Note: src/androidTest/AndroidManifest.xml is not needed as it is created automatically.

[Android插件對於Android項目還指定了一些其餘的目錄,注意test目錄下的AndroidManifest.xml 文件不須要提供,由於它會自動建立,後面會提到爲何]

Configuring the Structure

[當咱們的項目本來的目錄結構和上面默認的目錄結構不一樣時,咱們能夠進行配置,使用sourceSets 節點來修改目錄結構]

When the default project structure isn’t adequate, it is possible to configure it. According to the Gradle documentation, reconfiguring the sourceSets for a Java project can be done with the following:

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

Note: srcDir will actually add the given folder to the existing list of source folders (this is not mentioned in the Gradle documentation but this is actually the behavior).

[srcDir 會自動將給定的目錄加入到默認的已有的源碼目錄列表中,然而srcDirs 會覆蓋默認的源碼目錄設置]

To replace the default source folders, you will want to use srcDirs instead, which takes an array of path. This also shows a different way of using the objects involved:

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

For more information, see the Gradle documentation on the Java plugin here.

[Android插件使用和上面類似的語法來完成配置,只不過它的sourceSets 節點是定義在 android 中的]

The Android plugin uses a similar syntaxes, but because it uses its own sourceSets, this is done within the android object.

Here’s an example, using the old project structure for the main code and remapping the androidTest sourceSet to the tests folder:

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: because the old structure put all source files (java, aidl, renderscript, and java resources) in the same folder, we need to remap all those new components of the sourceSet to the same src folder.

[setRoot() 會將整個sourceSet包括其中的子目錄一塊兒移動到新的目錄中,這是Android插件特定的,Java插件沒有此功能]

Note: setRoot() moves the whole sourceSet (and its sub folders) to a new folder. This moves src/androidTest/* to tests/*

This is Android specific and will not work on Java sourceSets.

The ‘migrated’ sample shows this. [?]

Build Tasks

General Tasks

[使用plugin的好處是它會自動地幫咱們建立一些默認的build task]

Applying a plugin to the build file automatically creates a set of build tasks to run. Both the Java plugin and the Android plugin do this.

The convention for tasks is the following: [下面是默認的build tasks]

assemble The task to assemble the output(s) of the project
check The task to run all the checks.
build This task does both assemble and check
clean This task cleans the output of the project

[任務assemble,check,build實際上什麼都沒有作,它們只是anchor task,須要添加實際的task它們才知道如何工做,這樣的話就能夠無論你是什麼類型的項目均可以調用相同名稱的build task。例如若是使用了findbugs 插件的話,它會自動建立一個新的task,並且check task會依賴它,也就有是說,每當check task執行的時候,這個新的task都會被調用而執行]

The tasks assemble, check and build don’t actually do anything. They are anchor tasks for the plugins to add actual tasks that do the work.

This allows you to always call the same task(s) no matter what the type of project is, or what plugins are applied.

For instance, applying the findbugs plugin will create a new task and make check depend on it, making it be called whenever the check task is called.

From the command line you can get the high level task running the following command: gradle tasks
For a full list and seeing dependencies between the tasks run: gradle tasks --all

[在Android Studio的Terminal中運行結果以下]

image

Note: Gradle automatically monitor the declared inputs and outputs of a task. Running the build twice without change will make Gradle report all tasks as UP-TO-DATE, meaning no work was required. This allows tasks to properly depend on each other without requiring unneeded build operations.

[Gradle會監視一個任務的輸入和輸出,重複運行build結果都沒有變化的話Gradle會提示全部的任務都是UP-TO-DATE,這樣能夠避免沒必要要的build操做]

Java project tasks

[Java插件主要建立了兩個新的task,其中jar task是assemble task的依賴項,test task是check task的依賴項]

The Java plugin creates mainly two tasks, that are dependencies of the main anchor tasks:

assemble -> jar This task creates the output.
check -> test This task runs the tests.

[任務jar直接或者間接地依賴其餘的任務,例如用來編譯Java代碼的任務classes; 測試代碼是由testClasses 任務來編譯的,可是你不須要去調用這個task,由於test 任務依賴於testClassesclasses 任務]

The jar task itself will depend directly and indirectly on other tasks: classes for instance will compile the Java code.

** The tests are compiled with testClasses, but it is rarely useful to call this as test depends on it (as well as classes). **

In general, you will probably only ever call assemble or check, and ignore the other tasks.

You can see the full set of tasks and their descriptions for the Java plugin here.

Android tasks

The Android plugin use the same convention to stay compatible with other plugins, and adds an additional anchor task:

assemble The task to assemble the output(s) of the project
check The task to run all the checks.
connectedCheck Runs checks that requires a connected device or emulator, they will run on all connected devices in parallel. [在已鏈接的設備和模擬器上並行運行check任務]
deviceCheck Runs checks using APIs to connect to remote devices. This is used on CI servers. [使用APIs來鏈接遠程設備以運行check任務]
build This task does both assemble and check
clean This task cleans the output of the project

The new anchor tasks are necessary in order to be able to run regular checks without needing a connected device.Note that build does not depend on deviceCheck, or connectedCheck.

[任務build並不依賴deviceCheck和connectedCheck這兩個任務]

An Android project has at least two outputs: a debug APK and a release APK. Each of these has its own anchor task to facilitate building them separately:

[Android項目至少有兩個輸出:一個debug模式的APK,另外一個是release模式deAPK,每種模式都有本身的anchor task以便於將它們的build過程分開]

assemble
assembleDebug
assembleRelease

They both depend on other tasks that execute the multiple steps needed to build an APK. The assemble task depends on both, so calling it will build both APKs.

Tip: Gradle support camel case shortcuts for task names on the command line.

[Gradle支持在命令行中使用某個task的名稱的camel case縮寫調用這個task]

For instance: gradle aR is the same as typing gradle assembleRelease,as long as no other task match ‘aR’

The check anchor tasks have their own dependencies:

check
lint
connectedCheck
connectedAndroidTest
connectedUiAutomatorTest(not implemented yet)
deviceCheck

This depends on tasks created when other plugins implement test extension points.

Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing).

[Android插件還會對全部build type建立它們的install/uninstall 任務,只要它們能夠被安裝,安裝須要簽名]

Basic Build Customization

The Android plugin provides a broad DSL to customize most things directly from the build system.

Manifest entries

[經過DSL咱們能夠在build.gradle 文件中指定那些定義在AndroidManifest文件中的內容,不過可以指定的內容有限]

Through the DSL it is possible to configure the following manifest entries:

minSdkVersion
targetSdkVersion
versionCode
versionName
applicationId (the effective packageName -- see ApplicationId versus PackageName for more information)
Package Name for the test application
Instrumentation test runner

Example:

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        versionCode 12
        versionName "2.0"
        minSdkVersion 16
        targetSdkVersion 16
    }
}

The defaultConfig element inside the android element is where all this configuration is defined.

Previous versions of the Android Plugin used packageName to configure the manifest 'packageName' attribute. Starting in 0.11.0, you should use applicationId in the build.gradle to configure the manifest 'packageName' entry. This was disambiguated to reduce confusion between the application's packageName (which is its ID) and java packages.

[從Gradle Plugin 0.11.0 版本開始在build.gradle 文件中使用applicationId 而不是 packageName 來指定AndroidManifest文件中的packageName]

The power of describing it in the build file is that it can be dynamic.
For instance, one could be reading the version name from a file somewhere or using some custom logic:

[將上面那些內容定義在build文件中的魔力就在於它們能夠是動態的,以下所示]

def computeVersionName() {
    ...
}

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        versionCode 12
        versionName computeVersionName()
        minSdkVersion 16
        targetSdkVersion 16
    }
}

[注意不要使用當前域中已有的getter方法做爲自定義的函數名,不然會發生衝突]

Note: Do not use function names that could conflict with existing getters in the given scope. For instance instance defaultConfig { ...} calling getVersionName() will automatically use the getter of defaultConfig.getVersionName() instead of the custom method.

If a property is not set through the DSL, some default value will be used. Here’s a table of how this is processed.

image

[第2列是當你在build script中使用自定義邏輯去查詢第1列元素對應的默認結果,若是結果不是你想要的話,你能夠指定另外一個結果,可是在build時若是這個結果是null的話,build系統就會使用第3列中的結果]

The value of the 2nd column is important if you use custom logic in the build script that queries these properties. For instance, you could write:

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

If the value remains null, then it is replaced at build time by the actual default from column 3, but the DSL element does not contain this default value so you can't query against it.

This is to prevent parsing the manifest of the application unless it’s really needed.

Build Types

[默認狀況下,Android插件會自動將原項目編譯成debug和release兩個版本,它們的區別在於調試程序的功能和APK的簽名方式。debug版本使用key/certificate 來簽名,而release版本在build過程當中並不簽名,它的簽名過程發生在後面。Android插件容許咱們自定義build type]

By default, the Android plugin automatically sets up the project to build both a debug and a release version of the application.

These differ mostly around the ability to debug the application on a secure (non dev) devices, and how the APK is signed.

The debug version is signed with a key/certificate that is created automatically with a known name/password (to prevent required prompt during the build). The release is not signed during the build, this needs to happen after.

This configuration is done through an object called a BuildType. By default, 2 instances are created, a debug and a release one.

The Android plugin allows customizing those two instances as well as creating other Build Types. This is done with the buildTypes DSL container:

android {
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }

        jnidebug.initWith(buildTypes.debug)
        jnidebug {
            packageNameSuffix ".jnidebug"
            jnidebugBuild true
        }
    }
}

The above snippet achieves the following:

Configures the default debug Build Type:

(1) set its package to be <app appliationId>.debug to be able to install both debug and release apk on the same device

(2) Creates a new BuildType called jnidebug and configure it to be a copy of the debug build type.

(3) Keep configuring the jnidebug, by enabling debug build of the JNI component, and add a different package suffix.

[在buildTypes容器中建立一個新的build type很簡單,要麼調用initWith() 方法繼承自某個build type或者直接使用花括號來配置它]

Creating new Build Types is as easy as using a new element under the buildTypes container, either to call initWith() or to configure it with a closure.

The possible properties and their default values are:

image

In addition to these properties, Build Types can contribute to the build with code and resources.

[對於每一個build type都會生成一個對應的sourceSet,默認的位置是src/<buildtypename>/ ,因此build type的名稱不能是main或者androidTest,並且它們相互之間不能重名]

For each Build Type, a new matching sourceSet is created, with a default location of src/<buildtypename>/

This means the Build Type names cannot be main or androidTest (this is enforced by the plugin), and that they have to be unique to each other.

Like any other source sets, the location of the build type source set can be relocated:

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

[相似其餘的sourceSet,build type的source set的位置也能夠從新定義,此外,對於每一個build type,都會自動建立一個名爲assemble<BuildTypeName> 的任務,並且自動稱爲assemble 任務的依賴項]

Additionally, for each Build Type, a new assemble<BuildTypeName> task is created.

The assembleDebug and assembleRelease tasks have already been mentioned, and this is where they come from. When the debug and release Build Types are pre-created, their tasks are automatically created as well.

The build.gradle snippet above would then also generate an assembleJnidebug task, and assemble would be made to depend on it the same way it depends on the assembleDebug and assembleRelease tasks.

Tip: remember that you can type gradle aJ to run the assembleJnidebug task.

Possible use case: [使用場景]

Permissions in debug mode only, but not in release mode
Custom implementation for debugging
Different resources for debug mode (for instance when a resource value is tied to the signing certificate).

[build type的code/resources的處理過程: (1)Manifest整合進app的Manifest; (2)code就做爲另外一個源碼目錄; (3)resources覆蓋原有的main resources]

The code/resources of the BuildType are used in the following way:

The manifest is merged into the app manifest
The code acts as just another source folder
The resources are overlayed over the main resources, replacing existing values.

Signing Configurations

Signing an application requires the following:

A keystore
A keystore password
A key alias name
A key password
The store type

The location, as well as the key name, both passwords and store type form together a Signing Configuration (type SigningConfig)

[對一個應用程序進行簽名須要5個信息,這些信息組合起來就是類型SigningConfig。默認狀況下,debug的配置使用了一個已知密碼的keystore和已知密碼的默認key,其中的keystore保存在$HOME/.android/debug.keystore 文件中,若是沒有的話它會自動被建立]

By default, there is a debug configuration that is setup to use a debug keystore, with a known password and a default key with a known password.The debug keystore is located in $HOME/.android/debug.keystore, and is created if not present.

The debug Build Type is set to use this debug SigningConfig automatically.It is possible to create other configurations or customize the default built-in one. This is done through the signingConfigs DSL container:

[默認狀況下,debug的build過程會自動使用debug SigningConfig,固然咱們能夠本身定義]

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 above snippet changes the location of the debug keystore to be at the root of the project. This automatically impacts any Build Types that are set to using it, in this case the debug Build Type.

It also creates a new Signing Config and a new Build Type that uses the new configuration.

[只有當debug keystore是放在默認的位置,即便修改了keystore文件的名稱,keystore也會被自動建立,可是若是改變了默認位置的話則不會被自動建立。此外,設置keystore的位置通常使用相對於項目根目錄的路徑,雖然也可使用絕對路徑,可是並不推薦這樣作]

Note: Only debug keystores located in the default location will be automatically created. Changing the location of the debug keystore will not create it on-demand. Creating a SigningConfig with a different name that uses the default debug keystore location will create it automatically. In other words, it’s tied to the location of the keystore, not the name of the configuration.

Note: Location of keystores are usually relative to the root of the project, but could be absolute paths, though it is not recommended (except for the debug one since it is automatically created).

Note: If you are checking these files into version control, you may not want the password in the file. The following Stack Overflow post shows ways to read the values from the console, or from environment variables.
http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle

We'll update this guide with more detailed information later.

Running ProGuard

[對ProGuard的支持是經過Gradle plugin for ProGuard 4.10來實現的,給build type添加runProguard 屬性便可自動生成相應的task]

ProGuard is supported through the Gradle plugin for ProGuard version 4.10.

The ProGuard plugin is applied automatically, and the tasks are created automatically if the Build Type is configured to run ProGuard through the runProguard property.

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

    productFlavors {
        flavor1 {
        }
        flavor2 {
            proguardFile 'some-other-rules.txt'
        }
    }
}

Variants use all the rules files declared in their build type, and product flavors.

[默認狀況下有兩個proguard rule 文件,它們存放在Android SDK目錄中,默認是$ANDROID_HOME/tools/proguard/ 目錄下 ,使用getDefaultProguardFile() 能夠獲得它們的完整路徑]

There are 2 default rules files

proguard-android.txt
proguard-android-optimize.txt

They are located in the SDK. Using getDefaultProguardFile() will return the full path to the files. They are identical except for enabling optimizations.

Dependencies, Android Libraries and Multi-project setup

Gradle projects can have dependencies on other components. These components can be external binary packages, or other Gradle projects.

Dependencies on binary packages

Local packages

To configure a dependency on an external library jar, you need to add a dependency on the compile configuration.

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

android {
    ...
}

[注意dependencies是標準Gradle API的一部分,因此不是在android元素中聲明]

Note: the dependencies DSL element is part of the standard Gradle API and does not belong inside the android element.

[compile 的配置是用來編譯main application的,因此其中的全部元素都會加入到編譯的類路徑中,一樣也會打包進最終的APK中]

The compile configuration is used to compile the main application. Everything in it is added to the compilation classpath and also packaged in the final APK.

There are other possible configurations to add dependencies to:

compile: main application
androidTestCompile: test application
debugCompile: debug Build Type
releaseCompile: release Build Type.

[對應每一個build type都有一個對應的<buildtype>Compile, 它們的dependencies也均可以自行定義使其不一樣。若是但願不一樣的build type表現出不一樣的結果時,咱們即可以使用這種方式讓它們依賴不一樣的library]

Because it’s not possible to build an APK that does not have an associated Build Type, the APK is always configured with two (or more) configurations: compile and <buildtype>Compile.

Creating a new Build Type automatically creates a new configuration based on its name.

This can be useful if the debug version needs to use a custom library (to report crashes for instance), while the release doesn’t, or if they rely on different versions of the same library.

Remote artifacts

[Gradle支持Maven和Ivy資源庫]

Gradle supports pulling artifacts from Maven and Ivy repositories.

First the repository must be added to the list, and then the dependency must be declared in a way that Maven or Ivy declare their artifacts.

repositories {
    mavenCentral()
}


dependencies {
    compile 'com.google.guava:guava:11.0.2'
}

android {
    ...
}

[mavenCentral() 方法返回的就是Maven Repository的URL,Gradle同時支持remote 和 local repositories,此外,Gradle可以處理dependency之間的相互依賴,而後自動pull所須要的dependencies]

Note: mavenCentral() is a shortcut to specifying the URL of the repository. Gradle supports both remote and local repositories.

Note: Gradle will follow all dependencies transitively. This means that if a dependency has dependencies of its own, those are pulled in as well.

For more information about setting up dependencies, read the Gradle user guide here, and DSL documentation here.

Multi project setup

[使用multi-project setup可使得Gradle項目依賴其餘的Gradle項目,它一般是經過將全部的項目做爲某個指定的根項目的子目錄來實現的。]

Gradle projects can also depend on other gradle projects by using a multi-project setup.

A multi-project setup usually works by having all the projects as sub folders of a given root project.

For instance, given to following structure:

MyProject/
 + app/
 + libraries/
    + lib1/
    + lib2/

We can identify 3 projects. Gradle will reference them with the following name:

:app
:libraries:lib1
:libraries:lib2

Each projects will have its own build.gradle declaring how it gets built. Additionally, there will be a file called settings.gradle at the root declaring the projects.

[每一個項目都有本身的build.gradle 文件聲明它的build過程,此外,根項目下還有一個settings.gradle 文件用來指定這些子項目]

This gives the following structure:

MyProject/
 | settings.gradle
 + app/
    | build.gradle
 + libraries/
    + lib1/
       | build.gradle
    + lib2/
       | build.gradle

The content of settings.gradle is very simple:

include ':app', ':libraries:lib1', ':libraries:lib2'

This defines which folder is actually a Gradle project. [它聲明瞭哪一個目錄是一個Gradle項目]

The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:

dependencies {
    compile project(':libraries:lib1')
}

More general information about multi-project setup here.

Library projects

[若是前面例子中的兩個library projects都是Java項目的話,那麼app這個Android項目就使用它們的輸出jar文件便可,可是若是你須要引用library project中的資源或者代碼的話,那它們必須是Android Library Projects]

In the above multi-project setup, :libraries:lib1 and :libraries:lib2 can be Java projects, and the :app Android project will use their jar output.

However, if you want to share code that accesses Android APIs or uses Android-style resources, these libraries cannot be regular Java project, they have to be Android Library Projects.

Creating a Library Project

A Library project is very similar to a regular Android project with a few differences.

Since building libraries is different than building applications, a different plugin is used. Internally both plugins share most of the same code and they are both provided by the same com.android.tools.build.gradle jar.

[建立Library Project使用的是不一樣的插件,即android-library,它和android 插件共享不少的代碼(因此大部分的配置都和前面提到的如出一轍),而且這個插件的源碼也是在com.android.tools.build.gradle 這個jar包中]

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.6'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 15
}

This creates a library project that uses API 15 to compile. SourceSets, and dependencies are handled the same as they are in an application project and can be customized the same way.

Differences between a Project and a Library Project

[一個Library Project的主要輸出是一個aar包,它是編譯後的代碼與資源的集合,它一樣能夠生成test apk來獨立地測試這個library。Library Project和普通Project的assemble task是同樣的,因此它們的behave沒啥區別。此外,由於它能夠有不一樣的build type和product flavor,因此它能夠獲得不少個不一樣的aar]

A Library project's main output is an .aar package (which stands for Android archive). It is a combination of compile code (as a jar file and/or native .so files) and resources (manifest, res, assets).

**A library project can also generate a test apk to test the library independently from an application. **

The same anchor tasks are used for this (assembleDebug, assembleRelease) so there’s no difference in commands to build such a project.

For the rest, libraries behave the same as application projects. They have build types and product flavors, and can potentially generate more than one version of the aar.

[大多數的build type的配置都不會應用於Library Project中,固然它仍是能夠進行配置的]

Note that most of the configuration of the Build Type do not apply to library projects. However you can use the custom sourceSet to change the content of the library depending on whether it’s used by a project or being tested.

Referencing a Library

Referencing a library is done the same way any other project is referenced:

dependencies {
    compile project(':libraries:lib1')
    compile project(':libraries:lib2')
}

Note: if you have more than one library, then the order will be important. This is similar to the old build system where the order of the dependencies in the project.properties file was important.

[注:若是你有不少的library projects,那麼你要根據它們相互之間的依賴關係肯定一個正確的順序,就相似之前build系統中的project.properties 文件同樣,之前須要以下地聲明android.library.reference]

android.library.reference.1=path/to/libraryproject

Library Publication

[默認狀況下,library project只會publish它的release variant,全部其餘的project都是引用這個variant,可是你仍是能夠經過配置defaultPublishConfig 控制將哪一個variant進行publish,並且你也能夠設置爲publish全部variant]

By default a library only publishes its release variant. This variant will be used by all projects referencing the library, no matter which variant they build themselves. This is a temporary limitation due to Gradle limitations that we are working towards removing.

You can control which variant gets published with

android {
    defaultPublishConfig "debug"
}

**Note that this publishing configuration name references the full variant name. Release and debug are only applicable when there are no flavors. ** If you wanted to change the default published variant while using flavors, you would write:

android {
    defaultPublishConfig "flavor1Debug"
}

It is also possible to publish all variants of a library. We are planning to allow this while using a normal project-to-project dependency (like shown above), but this is not possible right now due to limitations in Gradle (we are working toward fixing those as well).

Publishing of all variants are not enabled by default. To enable them:

android {
    publishNonDefault true
}

It is important to realize that publishing multiple variants means publishing multiple aar files, instead of a single aar containing multiple variants. Each aar packaging contains a single variant.

[publish一個variant意味着使得這個aar包做爲Gradle項目的輸出,它能夠用於publish到maven repository,也能夠被其餘項目做爲依賴項目被引用]

Publishing an variant means making this aar available as an output artifact of the Gradle project. This can then be used either when publishing to a maven repository, or when another project creates a dependency on the library project.

Gradle has a concept of default" artifact. This is the one that is used when writing:

compile project(':libraries:lib2')

To create a dependency on another published artifact, you need to specify which one to use:

dependencies {
    flavor1Compile project(path: ':lib1', configuration: 'flavor1Release')
    flavor2Compile project(path: ':lib1', configuration: 'flavor2Release')
}

Important: Note that the published configuration is a full variant, including the build type, and needs to be referenced as such.

Important: When enabling publishing of non default, the Maven publishing plugin will publish these additional variants as extra packages (with classifier). This means that this is not really compatible with publishing to a maven repository. You should either publish a single variant to a repository OR enable all config publishing for inter-project dependencies. [?]

相關文章
相關標籤/搜索