jcenter() 仓库比 mavenCentral() 仓库快,因此最好将jcenter 放前面,这样下载速度最快。
使用本地软件仓库:
repositories { flatDir { dirs 'lib' } flatDir { dirs 'lib1', 'lib2' } }
本地仓库里的jar包的使用方法:
dependencies {
compile name: 'name-of-jar'
}
或者:
dependencies {
compile files('libs/smack-core-4.2.0.jar')
}
也可以这样一次性的指定依赖某个目录中全部的jar文件:
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs') }
dependencies {
compile fileTree(include: ['**/*.jar'], dir: 'libs') // 将会搜寻包含所有子目录 }
gradle 里如何包含github的库:
1、先在root build.gradle (最上层 build.gradle)里加入:
allprojects { repositories { ... maven { url "https://jitpack.io" } } }
然后在子工程里加入:
dependencies { compile 'com.github.User:Repo:Tag' }
示例(上面的repo是包含 gradle/wrapper 的目录,一般是顶层目录):
compile 'com.github.VictorAlbertos.RxCache:core:1.4.6'
compile 'com.github.bumptech.glide:glide:3.7.0'
如果上面的还是不好弄,推荐一个简单的 jitpack.io 官网自己提供的获取导入格式的网址 :https://jitpack.io/#com.afollestad/material-dialogs
在github里显示tag: 点releases, 里面有tag。
build.gradle里有两个repositories, 一个是主repositories, 一个在buildscript中, 主repositories制定的是为了编译你的工程所依赖的仓库, buildscript中的指定的是运行gradle所依赖的仓库。
settings.gradle 文件里是规定要编译的项目列表。
如果不想执行某个action,可以用 -x 选项,如: ./gradlew build -x lint -x test, 则不执行 lint 和 test。
若编译出来的库没有source jar文件,则可以自己在library的build.gradle里添加如下的东西(添加到文件的最外围,不属于任何option):
task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' } task javadoc(type: Javadoc) { source = android.sourceSets.main.java.srcDirs classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from javadoc.destinationDir // options.encoding = 'UTF-8' } artifacts { archives javadocJar archives sourcesJar }
配置gradle使用maven的本地库的方法:
Maven中央仓库已经成为了Java开发者不可或缺的资源,Gradle既然有依赖管理,那必然也得用到仓库,这当然也包括了Maven中央仓库,就像这样:
repositories {
mavenLocal()
mavenCentral()
mavenRepo urls: "http://repository.sonatype.org/content/groups/forge/"
}
这段代码几乎不用解释,就是在Gradle中配置使用Maven本地仓库、中央仓库、以及自定义地址仓库。
maven 安装本地文件到本地仓库的方法:
$ mvn install:install-file -Dfile=/home/hzh/dls/kotlin-compiler-embeddable-1.0.4.jar -DgroupId=org.jetbrains.kotlin -DartifactId=kotlin-compiler-embeddable -Dversion=1.0.4 -Dpackaging=jar
maven 安装网络上的文件到本地仓库的方法:
$ mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -DrepoUrl=https://repo1.maven.org/maven2/net/zetetic/android-database-sqlcipher/3.5.4/ -Dartifact=android-database-sqlcipher-3.5.4.jar
查看一个jar文件的 groupId、artifactId及version的方法是解压该 jar 文件,查看该jar文件里的 pom.properties 或 pom.xml:
(或者你可以到 http://search.maven.org 去在线查)
$ jar xvf dl/guava-r09.jar $ vi META-INF/maven/com.google.guava/guava/pom.properties
eclipse 添加 gradle 插件,官方说明文档: https://github.com/eclipse/buildship/blob/master/docs/user/Installation.md, 即:buildship。
使用gradle编译时如果出现You have not accepted the license agreements of the following SDK components: 这个错误,可以这样解决:
$ mkdir {$ANDROID_HOME}/licenses $ cd {$ANDROID_HOME}/licenses $ echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" > android-sdk-license $ echo -e "\n84831b9409646a918e30573bab4c9c91346d8abd" > android-sdk-preview-license
就可以了。
gradle 脚本手动将aar加入构建系统的方法:
Please follow below steps to get it working ( I have tested it up to Android Studio 2.2)
Lets say you have kept aar file in libs folder. ( assume file name is cards.aar
)
then in app(一定要是app的,不是跟目录的build.gradle。由于是app的 build.gradle,因此可以不必加上allprojects {
这句) build.gradle
specify following and click sync project with Gradle files.
allprojects {
repositories { jcenter() flatDir { dirs 'libs' } } } dependencies { compile(name:'cards', ext:'aar') }
If everything goes well you will see library entry is made in build -> exploded-aar
Also note that if you are importing a .aar file from another project that has dependencies you'll need to include these in your build.gradle, too.
Gradle Plugin User Guide, (google's gradle user guide)
http://tools.android.com/tech-docs/new-build-system/user-guide
Introduction
DSL reference
If you are looking for a full list of options available in build.gradle files, please see the DSL reference.
|
- 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?
- Domain Specific Language (DSL) based on Groovy, used 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
Requirements
- Gradle 2.2
- SDK with Build Tools 19.0.0. Some features may require a more recent version.
Basic Project Setup
Simple build files
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.1.0"
}
buildscript { ... } configures the code driving the build. In this case, this declares that it uses the jCenter 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 1.3.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 com.android.application plugin is applied. This is the plugin used for building Android applications.
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.
Important: You should only apply the com.android.application 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. Examplelocal.properties file:
sdk.dir=/path/to/Android/Sdk
Project Structure
- src/main/
- src/androidTest/
- java/
- resources/
- AndroidManifest.xml
- res/
- assets/
- aidl/
- rs/
- jni/
- jniLibs/
Configuring the Structure
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: 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.
Build Tasks
General 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.
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
gradle tasks --all
Running the build task twice without making changes to your project, 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 unnecessary build operations.
Java project tasks
java
plugin, dependencies of the main anchor tasks:- assemble
- jar
This task creates the output.
- jar
- check
- test
This task runs the tests.
- test
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
- 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.
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
Tip: Gradle support camel case shortcuts for task names on the command line. For instance:
gradle aR
gradle assembleRelease
The check anchor tasks have their own dependencies:
- check
- lint
- connectedCheck
- connectedAndroidTest
- deviceCheck
- This depends on tasks created when other plugins implement test extension points.
- installDebug
- installRelease
- uninstallAll
- uninstallDebug
- uninstallRelease
- uninstallDebugAndroidTest
Basic Build Customization
Manifest entries
- minSdkVersion
- targetSdkVersion
- versionCode
- versionName
- applicationId (the effective packageName -- see ApplicationId versus PackageName for more information)
- testApplicationId (used by the test APK)
- testInstrumentationRunner
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
versionCode 12
versionName "2.0"
minSdkVersion 16
targetSdkVersion 23
}
}
The power of putting these manifest properties in the build file is that the values can be chosen dynamically. For instance, one could be reading the version name from a file or using other custom logic:
def computeVersionName() {
...
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
versionCode 12
versionName computeVersionName()
minSdkVersion 16
targetSdkVersion 23
}
}
defaultConfig { ...}
calling getVersionName()
will automatically use the getter of defaultConfig.getVersionName()
instead of the custom method.
Build Types
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)
applicationIdSuffix ".jnidebug"
jniDebuggable true
}
}
}
The above snippet achieves the following:
- Configures the default debug Build Type:
- set its package to be
.debug to be able to install both debug and release apk on the same device
- set its package to be
- 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. See the DSL Reference for a list of all properties that can be configured on a build type.
In addition to modifying build properties, Build Types can be used to add specific code and resources. For each Build Type, a new matching sourceSet is created, with a default location of src/
Like any other source sets, the location of the build type source set can be relocated:
android {
sourceSets.jnidebug.setRoot('foo/jnidebug')
}
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 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
- A keystore
- A keystore password
- A key alias name
- A key password
- The store type
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 SigningConfigautomatically.
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 {
signingConfig signingConfigs.myConfig
}
}
}
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).
Dependencies, Android Libraries and Multi-project setup
Dependencies on binary packages
Local packages
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
android {
...
}
Note: the dependencies DSL element is part of the standard Gradle API and does not belong inside the android element.
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.
Remote artifacts
repositories {
jcenter()
}
dependencies {
compile 'com.google.guava:guava:18.0'
}
android {
...
}
Note: jcenter() 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
MyProject/+ app/+ libraries/+ lib1/+ lib2/
: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. 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. It defines which folder is actually a Gradle project:
include ':app', ':libraries:lib1', ':libraries:lib2'
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
Creating a Library Project
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
}
Differences between a Project and a Library Project
Referencing a Library
dependencies {
compile project(':libraries:lib1')
compile project(':libraries:lib2')
}
Library Publication
android {
defaultPublishConfig "debug"
}
android {
defaultPublishConfig "flavor1Debug"
}
android {
publishNonDefault true
}
dependencies {
compile project(':libraries:lib2')
}
dependencies {
flavor1Compile project(path: ':lib1', configuration: 'flavor1Release')
flavor2Compile project(path: ':lib1', configuration: 'flavor2Release')
}
Testing
Unit testing
Basics and Configuration
There are a few values that can be configured for the test app, in order to configure the
- testApplicationId
- testInstrumentationRunner
-
testHandleProfiling
-
testFunctionalTest
android {
defaultConfig {
testApplicationId "com.test.foo"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
testHandleProfiling true
testFunctionalTest true
}
}
Additionally, the androidTest source set can be configured to have its own dependencies. By default, the application and its own dependencies are added to the test app classpath, but this can be extended with the snippet below:
dependencies {
androidTestCompile 'com.google.guava:guava:11.0.2'
}
Currently only one Build Type is tested. By default it is the debug Build Type, but this can be reconfigured with:
android {
...
testBuildType "staging"
}
Resolving conflicts between main and test APK
./gradlew :app:dependencies
and ./gradlew :app:androidDependencies.
Running tests
- Ensure the app and the test app are built (depending on assembleDebug and assembleDebugAndroidTest).
- Install both apps.
- Run the tests.
- Uninstall both apps.
Testing Android Libraries
Test reports
android {
...
testOptions {
resultsDir = "${project.buildDir}/foo/results"
}
}
Multi-projects reports
To do this, a different plugin is available in the same artifact. It can be applied with:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.6'
}
}
apply plugin: 'android-reporting'
Then from the root folder, the following command line will run all the tests and aggregate the reports:
gradle deviceCheck mergeAndroidReports --continue
Note: the --continue option ensure that all tests, from all sub-projects will be run even if one of them fails. Without it the first failing test will interrupt the run and not all projects may have their tests run.
Lint support
./gradlew lintRelease
, or for all variants (./gradlew lint
), in which case it produces a report which describes which specific variants a given issue applies to. You can configure lint by adding a lintOptions section like following. You typically only specify a few of these, see the DSL reference for all available options.
android {
lintOptions {
// turn off checking the given issue id's
disable 'TypographyFractions','TypographyQuotes'
// turn on the given issue id's
enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
// check *only* the given issue id's
check 'NewApi', 'InlinedApi'
}
}
Build Variants
There are two main use cases:
- Different versions of the same application
For instance, a free/demo version vs the “pro” paid application. - Same application packaged differently for multi-apk in Google Play Store.
See http://developer.android.com/google/play/publishing/multiple-apks.html for more information. - A combination of 1. and 2.
Product flavors
This new concept is designed to help when the differences are very minimum. If the answer to “Is this the same application?” is yes, then this is probably the way to go over Library Projects.
Product flavors are declared using a productFlavors DSL container:
android {
....
productFlavors {
flavor1 {
...
}
flavor2 {
...
}
}
}
Note: The name of the flavors cannot collide with existing Build Type names, or with the androidTest and test source sets.
Build Type + Product Flavor = Build Variant
- Flavor1 - debug
- Flavor1 - release
- Flavor2 - debug
- Flavor2 - release
Product Flavor Configuration
android {
...
defaultConfig {
minSdkVersion 8
versionCode 10
}
productFlavors {
flavor1 {
applicationId "com.example.flavor1"
versionCode 20
}
flavor2 {
applicationId "com.example.flavor2"
minSdkVersion 14
}
}
}
defaultConfig provides the base configuration for all flavors and each flavor can override any value. In the example above, the configurations end up being:
- flavor1
- applicationId: com.example.flavor1
- minSdkVersion: 8
- versionCode: 20
- flavor2
- applicationId: com.example.flavor2
- minSdkVersion: 14
- versionCode: 10
Sourcesets and Dependencies
- android.sourceSets.flavor1
Location src/flavor1/ - android.sourceSets.flavor2
Location src/flavor2/ - android.sourceSets.androidTestFlavor1
Location src/androidTestFlavor1/ - android.sourceSets.androidTestFlavor2
Location src/androidTestFlavor2/
- All source code (src/*/java) are used together as multiple folders generating a single output.
- Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or permissions, similarly to Build Types.
- All resources (Android res and assets) are used using overlay priority where the Build Type overrides the Product Flavor, which overrides the main sourceSet.
- Each Build Variant generates its own R class (or other generated source code) from the resources. Nothing is shared between variants.
dependencies {
flavor1Compile "..."
}
- android.sourceSets.flavor1Debug
Location src/flavor1Debug/ - android.sourceSets.flavor1Release
Location src/flavor1Release/ - android.sourceSets.flavor2Debug
Location src/flavor2Debug/ - android.sourceSets.flavor2Release
Location src/flavor2Release/
Building and Tasks
When Product Flavors are used, more assemble-type tasks are created. These are:
- assemble
- assemble
- assemble
#2 allows building all APKs for a given Build Type. For instance assembleDebug will build both Flavor1Debug and Flavor2Debug variants.
#3 allows building all APKs for a given flavor. For instance assembleFlavor1 will build both Flavor1Debug and Flavor1Release variants.
The task assemble will build all possible variants.
Multi-flavor variants
For instance, multi-apk support in Google Play supports 4 different filters. Creating different APKs split on each filter requires being able to use more than one dimension of Product Flavors.
Consider the example of a game that has a demo and a paid version and wants to use the ABI filter in the multi-apk support. With 3 ABIs and two versions of the application, 6 APKs needs to be generated (not counting the variants introduced by the different Build Types).
However, the code of the paid version is the same for all three ABIs, so creating simply 6 flavors is not the way to go.
Instead, there are two dimensions of flavors, and variants should automatically build all possible combinations.
android {
...
flavorDimensions "abi", "version"
productFlavors {
freeapp {
dimension "version"
...
}
paidapp {
dimension "version"
...
}
arm {
dimension "abi"
...
}
mips {
dimension "abi"
...
}
x86 {
dimension "abi"
...
}
}
}
From the following dimensioned Product Flavors [freeapp, paidapp] and [x86, arm, mips] and the [debug, release] Build Types, the following build variants will be created:
- x86-freeapp-debug
- x86-freeapp-release
- arm-freeapp-debug
- arm-freeapp-release
- mips-freeapp-debug
- mips-freeapp-release
- x86-paidapp-debug
- x86-paidapp-release
- arm-paidapp-debug
- arm-paidapp-release
- mips-paidapp-debug
- mips-paidapp-release
Each variant is configured by several Product Flavor objects:
- android.defaultConfig
- One from the abi dimension
- One from the version dimension
The flavor dimension is defined with higher priority first. So in this case:
abi > version > defaultConfig
- android.sourceSets.x86Freeapp
Location src/x86Freeapp/ - android.sourceSets.armPaidapp
Location src/armPaidapp/ - etc...
Testing
Testing multi-flavors project is very similar to simpler projects.The androidTest sourceset is used for common tests across all flavors, while each flavor can also have its own tests.
As mentioned above, sourceSets to test each flavor are created:
- android.sourceSets.androidTestFlavor1
Location src/androidTestFlavor1/ - android.sourceSets.androidTestFlavor2
Location src/androidTestFlavor2/
Similarly, those can have their own dependencies:
dependencies {
androidTestFlavor1Compile "..."
}
Each flavor has its own task to run tests: androidTest
- androidTestFlavor1Debug
- androidTestFlavor2Debug
- assembleFlavor1Test
- installFlavor1Debug
- installFlavor1Test
- uninstallFlavor1Debug
- ...
The location of the test results and reports is as follows, first for the per flavor version, and then for the aggregated one:
- build/androidTest-results/flavors/
- build/androidTest-results/all/
- build/reports/androidTests/flavors
- build/reports/androidTests/all/
BuildConfig
BuildConfig
that contains constant values used when building a particular variant. You can inspect the values of these constants to change behavior in different variants, e.g.:private void javaCode() {
if (BuildConfig.FLAVOR.equals("paidapp")) {
doIt();
else {
showOnlyInPaidAppDialog();
}
}
Here are the values that BuildConfig contains:
boolean DEBUG
– if the build is debuggable.int VERSION_CODE
String VERSION_NAME
String APPLICATION_ID
String BUILD_TYPE
– name of the build type, e.g. "release"String FLAVOR
– name of the flavor, e.g. "paidapp"
String FLAVOR = "armFreeapp"
String FLAVOR_abi = "arm"
String FLAVOR_version = "freeapp"
Filtering Variants
variantFilter
closure, like this:
productFlavors {
realData
fakeData
}
variantFilter { variant ->
def names = variant.flavors*.name
if (names.contains("fakeData") && variant.buildType.name == "release") {
variant.ignore = true
}
}
}
realDataDebug
realDataRelease
fakeDataDebug
variant
that you can check.
Advanced Build Customization
Running ProGuard
android {
buildTypes {
release {
minifyEnabled true
proguardFile getDefaultProguardFile('proguard-android.txt')
}
}
productFlavors {
flavor1 {
}
flavor2 {
proguardFile 'some-other-rules.txt'
}
}
}
- proguard-android.txt
- proguard-android-optimize.txt
Shrinking Resources
The classes task is the one that compile the Java source code.
It’s easy to access from build.gradle by simply using classes in a script. This is a shortcut for project.tasks.classes.
In Android projects, this is a bit more complicated because there could be a large number of the same task and their name is generated based on the Build Types and Product Flavors.
In order to fix this, the android object has two properties:
- applicationVariants (only for the app plugin)
- libraryVariants (only for the library plugin)
- testVariants (for both plugins)
Note that accessing any of these collections will trigger the creations of all the tasks. This means no (re)configuration should take place after accessing the collections.
The DomainObjectCollection gives access to all the objects directly, or through filters which can be convenient.
android.applicationVariants.all { variant ->
....
}
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. |
The ApplicationVariant class adds the following:
Property Name | Property Type | Description |
buildType | BuildType | The BuildType of the variant. |
productFlavors | List |
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. |
The LibraryVariant class adds the following:
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. |
The TestVariant class adds the following:
Property Name | Property Type | Description |
buildType | BuildType | The BuildType of the variant. |
productFlavors | List |
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.
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.
Setting language level
compileOptions
block to choose the language level used by the compiler. The default is chosen based on the compileSdkVersion
value.
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_6
targetCompatibility JavaVersion.VERSION_1_6
}
}