Android Tools Project Site | Search this site |
|
|
Technical docs > New Build System > Gradle Plugin User Guide
|
Contents
IntroductionThis documentation is for the Gradle plugin version 0.9. Earlier versions may differ due to non-compatible we are introducing before 1.0. Goals of the new Build SystemThe goals of the new build system are:
Why Gradle?Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.
Requirements
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:
This applies the Java plugin, which is packaged with Gradle. The plugin provides everything to build and test Java applications.
There are 3 main areas to this Android build file: 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. 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:
Inside each of these folders exists folder for each source components.
For the Android plugin, extra files and folders specific to Android:
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:
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).
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:
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. 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:
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:
For a full list and seeing dependencies between the tasks run:
Note: Gradle automatically monitor the declared inputs and outputs of a task. Java project tasksThe Java plugin creates mainly two tasks, that are dependencies of the main anchor tasks:
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:
The new anchor tasks are necessary in order to be able to run regular checks without needing a connected device.
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.
is the same as typing
as long as no other task match ‘aR’
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:
Example:
The defaultConfig element inside the android
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.
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. 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 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. 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 above snippet achieves the following:
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: In addition to these properties, Build Types can contribute to the build with code and resources. For each Build Type, a new matching sourceSet is created, with a default location of
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.
Additionally, for each Build Type, a new assemble<BuildTypeName> task is created.
The code/resources of the BuildType are used in the following way:
Signing ConfigurationsSigning an application requires the following:
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 signingConfigsDSL container:
The above snippet changes the location of the debug keystore to be at the root of the project. This automatically impacts anyBuild Types that are set to using it, in this case the debug Build Type.
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 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.
There are 2 default rules files
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 setupGradle projects can have dependencies on other components. These components can be external binary packages, or other Gradle projects. Dependencies on binary packagesLocal packagesTo configure a dependency on an external library jar, you need to add a dependency on the compile configuration.
Note: the dependencies DSL element is part of the standard Gradle API and does not belong inside the android element.
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 artifactsGradle supports pulling artifacts from Maven and Ivy repositories.
Note: mavenCentral() is a shortcut to specifying the URL of the repository. Gradle supports both remote and local repositories. Multi project setupGradle projects can also depend on other gradle projects by using a multi-project setup.
We can identify 3 projects. Gradle will reference them with the following name:
Each projects will have its own build.gradle declaring how it gets built.
The content of settings.gradle is very simple:
This defines which folder is actually a Gradle project. The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies:
More general information about multi-project setup here. Library projectsIn 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 ProjectA Library project is very similar to a regular Android project with a few differences.
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 ProjectA 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. 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 LibraryReferencing a library is done the same way any other project is referenced:
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 PublicationBy 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
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:
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:
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. 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:
To create a dependency on another published artifact, you need to specify which one to use:
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. TestingBuilding a test application is integrated into the application project. There is no need for a separate test project anymore. Basics and ConfigurationAs mentioned previously, next to the main sourceSet is the androidTest sourceSet, located by default in src/androidTest/
As seen previously, those are configured in the defaultConfig
The value of the targetPackage attribute of the instrumentation node in the test application manifest is automatically filled with the package name of the tested app, even if it is customized through the defaultConfig and/or the Build Typeobjects. This is one of the reason the manifest is generated automatically.
The test app is built by the task assembleTest. It is not a dependency of the main assemble task, and is instead called automatically when the tests are set to run.
Running testsAs mentioned previously, checks requiring a connected device are launched with the anchor task called connectedCheck. This depends on the task androidTest and therefore will run it. This task does the following:
If more than one device is connected, all tests are run in parallel on all connected devices. If one of the test fails, on any device, the build will fail. All test results are stored as XML files under
(This is similar to regular jUnit results that are stored under build/test-results)
The value of android.testOptions.resultsDir is evaluated with Project.file(String) Testing Android LibrariesTesting Android Library project is done exactly the same way as application projects. Test reportsWhen running unit tests, Gradle outputs an HTML report to easily look at the results. Single projectsThe project is automatically generated upon running the tests. Its default location is
This is similar to the jUnit report location, which is build/reports/tests, or other reports usually located inbuild/reports/<plugin>/
The report will aggregate tests that ran on different devices. Multi-projects reportsIn a multi project setup with application(s) and library(ies) projects, when running all tests at the same time, it might be useful to generate a single reports for all tests.
This should be applied to the root project, ie in build.gradle next to settings.gradle
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 supportAs of version 0.7.0, you can run lint for a specific variant, or for all variants, 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; this section shows all the available options.
Build VariantsOne goal of the new build system is to enable creating different versions of the same application.
The goal was to be able to generate these different APKs from the same project, as opposed to using a single Library Projects and 2+ Application Projects. Product flavorsA product flavor defines a customized version of the application build by the project. A single project can have different flavors which change the generated application.
This creates two flavors, called flavor1 and flavor2. Build Type + Product Flavor = Build VariantAs we have seen before, each Build Type generates a new APK.
Projects with no flavors still have Build Variants, but the single default flavor/config is used, nameless, making the list of variants similar to the list of Build Types. Product Flavor ConfigurationEach flavors is configured with a closure:
Note that the android.productFlavors.* objects are of type ProductFlavor which is the same type as theandroid.defaultConfig object. This means they share the same properties.
Usually, the Build Type configuration is an overlay over the other configuration. For instance, the Build Type's packageNameSuffix is appended to the Product Flavor's packageName. There are cases where a setting is settable on both the Build Type and the Product Flavor. In this case, it’s is on a case by case basis. For instance, signingConfig is one of these properties. This enables either having all release packages share the same SigningConfig, by settingandroid.buildTypes.release.signingConfig, or have each release package use their own SigningConfig by setting eachandroid.productFlavors.*.signingConfig objects separately. Sourcesets and DependenciesSimilar to Build Types, Product Flavors also contribute code and resources through their own sourceSets.
Those sourceSets are used to build the APK, alongside android.sourceSets.main and the Build Type sourceSet. The following rules are used when dealing with all the sourcesets used to build a single APK:
Finally, like Build Types, Product Flavors can have their own dependencies. For instance, if the flavors are used to generate a ads-based app and a paid app, one of the flavors could have a dependency on an Ads SDK, while the other does not.
In this particular case, the file src/flavor1/AndroidManifest.xml
Additional sourcesets are also created for each variants:
These have higher priority than the build type sourcesets, and allow customization at the variant level. Building and TasksWe previously saw that each Build Type creates its own assemble<name> task, but that Build Variants are a combination of Build Type and Product Flavor.
#1 allows directly building a single variant. For instance assembleFlavor1Debug. #2 allows building all APKs for a given Build Type. For instance assembleDebug will build both Flavor1Debug andFlavor2Debug variants. #3 allows building all APKs for a given flavor. For instance assembleFlavor1 will build both Flavor1Debug andFlavor1Release variants. The task assemble will build all possible variants. TestingTesting 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:
Similarly, those can have their own dependencies:
Running the tests can be done through the main deviceCheck anchor task, or the main androidTest tasks which acts as an anchor task when flavors are used.
Similarly, test APK building tasks and install/uninstall tasks are per variant:
Finally the HTML report generation supports aggregation by flavor. The location of the test results and reports is as follows, first for the per flavor version, and then for the aggregated one:
Customizing either path, will only change the root folder and still create sub folders per-flavor and aggregated results/reports. Multi-flavor variantsIn some case, one may want to create several versions of the same apps based on more than one criteria.
The android.flavorGroups array defines the possible groups, as well as the order. Each defined Product Flavor is assigned to a group.
The order of the group as defined by android.flavorGroups is very important. Each variant is configured by several Product Flavor objects:
The order of the group drives which flavor override the other, which is important for resources when a value in a flavor replaces a value defined in a lower priority flavor. The flavor groups is defined with higher priority first. So in this case:
Multi-flavors projects also have additional sourcesets, similar to the variant sourcesets but without the build type:
These allow customization at the flavor-combination level. They have higher priority than the basic flavor sourcesets, but lower priority than the build type sourcesets. Advanced Build CustomizationBuild optionsJava Compilation options
Default value is “1.6”. This affect all tasks compiling Java source code. aapt options
This affects all tasks using aapt. dex options
This affects all tasks using dex. Manipulating tasksBasic Java projects have a finite set of tasks that all work together to create an output.
All three return a DomainObjectCollection of ApplicationVariant, LibraryVariant, and TestVariant objects respectively. 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.
All three variant classes share the following properties: The ApplicationVariant class adds the following: The LibraryVariant class adds the following: The TestVariant class adds the following: Property Name Default value in DSL object Default valueversionCode -1 value from manifest if presentversionName null value from manifest if presentminSdkVersion -1 value from manifest if presenttargetSdkVersion -1 value from manifest if presentapplicationId null value from manifest if presenttestApplicationId null applicationId + “.test”testInstrumentationRunner null android.test.InstrumentationTestRunnersigningConfig null null proguardFile N/A (set only) N/A (set only) proguardFiles N/A (set only) N/A (set only) API for Android specific task types.
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. BuildType and Product Flavor property referencecoming soon. For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation. Using sourceCompatibility 1.7With 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:
Note that you can use
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.) |