Gradle Plugin User Guide
2015-05-01 07:57
405 查看
翻土堆不易,拷贝下来以备查看。
2015-05-01 拷贝于http://tools.android.com/tech-docs/new-build-system/user-guide
-----------------------------------------------------------------------------
Gradle Plugin User Guide
Contents 1 Introduction 1.1 Why Gradle? 2 Requirements 3 Basic Project 3.1 Simple build files 3.2 Project Structure 3.2.1 Configuring the Structure 3.3 Build Tasks 3.3.1 General Tasks 3.3.2 Java project tasks 3.3.3 Android tasks 3.4 Basic Build Customization 3.4.1 Manifest entries 3.4.2 Build Types 3.4.3 Signing Configurations 3.4.4 Running ProGuard 3.4.5 Shrinking Resources 4 Dependencies, Android Libraries and Multi-project setup 4.1 Dependencies on binary packages 4.1.1 Local packages 4.1.2 Remote artifacts 4.2 Multi project setup 4.3 Library projects 4.3.1 Creating a Library Project 4.3.2 Differences between a Project and a Library Project 4.3.3 Referencing a Library 4.3.4 Library Publication 5 Testing 5.1 Unit Testing 5.2 For the experimental unit testing support added in 1.1, please see this page. The rest of this section describes "instrumentation tests" that can run on a real device (or an emulator) and require a separate, testing APK to be built. 5.3 Basics and Configuration 5.4 Running tests 5.5 Testing Android Libraries 5.6 Test reports 5.6.1 Single projects 5.6.2 Multi-projects reports 5.7 Lint support 6 Build Variants 6.1 Product flavors 6.2 Build Type + Product Flavor = Build Variant 6.3 Product Flavor Configuration 6.4 Sourcesets and Dependencies 6.5 Building and Tasks 6.6 Testing 6.7 Multi-flavor variants 7 Advanced Build Customization 7.1 Build options 7.1.1 Java Compilation options 7.1.2 aapt options 7.1.3 dex options 7.2 Manipulating tasks 7.3 BuildType and Product Flavor property reference 7.4 Using sourceCompatibility 1.7 IntroductionGoals of the new Build SystemThe goals of the new build system are: 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 integration Why Gradle?Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.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 RequirementsGradle 1.10 or 1.11 or 1.12 with the plugin 0.11.1SDK with Build Tools 19.0.0. Some features may require a more recent version. Basic ProjectA Gradle project describes its build in a file called build.gradle located in the root folder of the project.Simple build filesThe 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: 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. Then, the android plugin is applied like the Java plugin earlier. 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. 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. 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. Project StructureThe basic build files above expect a default folder structure. Gradle follows the concept of convention over configuration, providing sensible default option values when possible.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. Configuring the StructureWhen 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). 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. 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. 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 TasksGeneral TasksApplying 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: 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 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 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. Java project tasksThe 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. 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 tasksThe 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. deviceCheck Runs checks using APIs to connect to remote devices. This is used on CI servers. 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. 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: 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. 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). Basic Build CustomizationThe Android plugin provides a broad DSL to customize most things directly from the build system.Manifest entriesThrough 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. 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: def computeVersionName() { ... } android { compileSdkVersion 19 buildToolsVersion "19.0.0" defaultConfig { versionCode 12 versionName computeVersionName() minSdkVersion 16 targetSdkVersion 16 } } 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.
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 TypesBy 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" jniDebuggable true } } } The above snippet achieves the following: Configures the default debug Build Type: set its package to be <app appliationId>.debug to be able to install both debug and release apk on the same device Creates a new BuildType called jnidebug and configure it to be a copy of the debug build type. Keep configuring the jnidebug, by enabling debug build of the JNI component, and add a different package suffix. 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:
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') } 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 theassembleDebug 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). 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 ConfigurationsSigning 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) 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: 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 } } } 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. 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 aSigningConfig 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, thought 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 ProGuardProGuard 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 minifyEnabled property.android { buildTypes { release { minifyEnabled 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. 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. Shrinking ResourcesYou can also remove unused resources, automatically, at build time. For more information, see the ResourceShrinking document. Dependencies, Android Libraries and Multi-projectGradle projects can have dependencies on other components. These components can be external binary packages, or other Gradle projects. |
Property Name | Property Type | Description |
name | String | The name of the variant. Guaranteed to be unique. |
description | String | Human readable description of the variant. |
dirName | String | subfolder name for the variant. Guaranteed to be unique. Maybe more than one folder, ie “debug/flavor1” |
baseName | String | Base name of the output(s) of the variant. Guaranteed to be unique. |
outputFile | File | The output of the variant. This is a read/write property |
processManifest | ProcessManifest | The task that processes the manifest. |
aidlCompile | AidlCompile | The task that compiles the AIDL files. |
renderscriptCompile | RenderscriptCompile | The task that compiles the Renderscript files. |
mergeResources | MergeResources | The task that merges the resources. |
mergeAssets | MergeAssets | The task that merges the assets. |
processResources | ProcessAndroidResources | The task that processes and compile the Resources. |
generateBuildConfig | GenerateBuildConfig | The task that generates the BuildConfig class. |
javaCompile | JavaCompile | The task that compiles the Java code. |
processJavaResources | Copy | The task that process the Java resources. |
assemble | DefaultTask | The assemble anchor task for this variant. |
Property Name | Property Type | Description |
buildType | BuildType | The BuildType of the variant. |
productFlavors | List<ProductFlavor> | The ProductFlavors of the variant. Always non Null but could be empty. |
mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors |
signingConfig | SigningConfig | The SigningConfig object used by this variant |
isSigningReady | boolean | true if the variant has all the information needed to be signed. |
testVariant | BuildVariant | The TestVariant that will test this variant. |
dex | Dex | The task that dex the code. Can be null if the variant is a library. |
packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. |
zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. |
install | DefaultTask | The installation task. Can be null. |
uninstall | DefaultTask | The uninstallation task. |
Property Name | Property Type | Description |
buildType | BuildType | The BuildType of the variant. |
mergedFlavor | ProductFlavor | The defaultConfig values |
testVariant | BuildVariant | The Build Variant that will test this variant. |
packageLibrary | Zip | The task that packages the Library AAR archive. Null if not a library. |
Property Name | Property Type | Description |
buildType | BuildType | The BuildType of the variant. |
productFlavors | List<ProductFlavor> | The ProductFlavors of the variant. Always non Null but could be empty. |
mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors |
signingConfig | SigningConfig | The SigningConfig object used by this variant |
isSigningReady | boolean | true if the variant has all the information needed to be signed. |
testedVariant | BaseVariant | The BaseVariant that is tested by this TestVariant. |
dex | Dex | The task that dex the code. Can be null if the variant is a library. |
packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. |
zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. |
install | DefaultTask | The installation task. Can be null. |
uninstall | DefaultTask | The uninstallation task. |
connectedAndroidTest | DefaultTask | The task that runs the android tests on connected devices. |
providerAndroidTest | DefaultTask | The task that runs the android tests using the extension API. |
ProcessManifest
File manifestOutputFile
AidlCompile
File sourceOutputDir
RenderscriptCompile
File sourceOutputDir
File resOutputDir
MergeResources
File outputDir
MergeAssets
File outputDir
ProcessAndroidResources
File manifestFile
File resDir
File assetsDir
File sourceOutputDir
File textSymbolOutputDir
File packageOutputFile
File proguardOutputFile
GenerateBuildConfig
File sourceOutputDir
Dex
File outputFolder
PackageApplication
File resourceFile
File dexFile
File javaResourceDir
File jniDir
File outputFile
To change the final output file use "outputFile" on the variant object directly.
ZipAlign
File inputFile
File outputFile
To change the final output file use "outputFile" on the variant object directly.
The API for each task type is limited due to both how Gradle works and how the Android plugin sets them up.
First, Gradle is meant to have the tasks be only configured for input/output location and possible optional flags. So here, the tasks only define (some of) the inputs/outputs.
Second, the input for most of those tasks is non-trivial, often coming from mixing values from the sourceSets, the Build Types, and the Product Flavors. To keep build files simple to read and understand, the goal is to let developers
modify the build by tweak these objects through the DSL, rather than diving deep in the inputs and options of the tasks and changing them.
Also note, that except for the ZipAlign task type, all other types require setting up private data to make them work. This means it’s not possible to manually create new tasks of these types.
This API is subject to change. In general the current API is around giving access to the outputs and inputs (when possible) of the tasks to add extra processing when required). Feedback is appreciated, especially around needs that may not have been foreseen.
For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation.
BuildType and Product Flavor property reference
coming soon.For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation.
Using sourceCompatibility 1.7
With Android KitKat (buildToolsVersion 19) you can use the diamond operator, multi-catch, strings in switches, try with resources, etc. To do this, add the following to your build file:android {
compileSdkVersion 19
buildToolsVersion "19.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Note that you can use
minSdkVersionwith a value earlier than 19, for all language features except try with resources. If you want to use try with resources, you will need to also use a
minSdkVersionof
19.
You also need to make sure that Gradle is using version 1.7 or later of the JDK. (And version 0.6.1 or later of the Android Gradle plugin.)
相关文章推荐
- 使用Android Studio和Gradle编译NDK项目之Experimental Plugin User Guide
- Gradle Plugin User Guide
- Gradle Plugin User Guide - Android
- gradle plugin user guide中文版
- Gradle Plugin User Guide
- Gradle Plugin for Android Development User Guide (2)
- Gradle Plugin User Guide
- 【Android Studio】Gradle Plugin User Guide
- Gradle Plugin User Guide 中文版
- Gradle Plugin User Guide翻译
- Gradle Plugin User Guide
- Gradle User Guide(1)
- flume User Guide翻译-logging raw data / plugin
- GradleUserGuide中文版 19)Plugins 20)插件规范 21)Java插件
- 【转】Gradle User Guide 中文版
- GradleUserGuide中文版 14)Tasks 15)文件操作
- Gradle User Guide(2)
- 【转】Gradle User Guide 中文版
- GradleUserGuide中文版 7)Java构建 8)依赖管理基础 9)Groovy入门
- Gradle-user guide-Installing-第四章 安装Gradle(译)