├── .gitignore ├── En └── README.md ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | _site/ 2 | -------------------------------------------------------------------------------- /En/README.md: -------------------------------------------------------------------------------- 1 | Gradle Plugin User Guide 中文版 2 | =========================== 3 | 4 | 5 | 目录 6 | 7 | 1 Introduction 8 | 1.1 Goals of the new Build System 9 | 1.2 Why Gradle? 10 | 2 Requirements 11 | 3 Basic Project 12 | 3.1 Simple build files 13 | 3.2 Project Structure 14 | 3.2.1 Configuring the Structure 15 | 3.3 Build Tasks 16 | 3.3.1 General Tasks 17 | 3.3.2 Java project tasks 18 | 3.3.3 Android tasks 19 | 3.4 Basic Build Customization 20 | 3.4.1 Manifest entries 21 | 3.4.2 Build Types 22 | 3.4.3 Signing Configurations 23 | 3.4.4 Running ProGuard 24 | 4 Dependencies, Android Libraries and Multi-project setup 25 | 4.1 Dependencies on binary packages 26 | 4.1.1 Local packages 27 | 4.1.2 Remote artifacts 28 | 4.2 Multi project setup 29 | 4.3 Library projects 30 | 4.3.1 Creating a Library Project 31 | 4.3.2 Differences between a Project and a Library Project 32 | 4.3.3 Referencing a Library 33 | 4.3.4 Library Publication 34 | 5 Testing 35 | 5.1 Basics and Configuration 36 | 5.2 Running tests 37 | 5.3 Testing Android Libraries 38 | 5.4 Test reports 39 | 5.4.1 Single projects 40 | 5.4.2 Multi-projects reports 41 | 5.5 Lint support 42 | 6 Build Variants 43 | 6.1 Product flavors 44 | 6.2 Build Type + Product Flavor = Build Variant 45 | 6.3 Product Flavor Configuration 46 | 6.4 Sourcesets and Dependencies 47 | 6.5 Building and Tasks 48 | 6.6 Testing 49 | 6.7 Multi-flavor variants 50 | 7 Advanced Build Customization 51 | 7.1 Build options 52 | 7.1.1 Java Compilation options 53 | 7.1.2 aapt options 54 | 7.1.3 dex options 55 | 7.2 Manipulating tasks 56 | 7.3 BuildType and Product Flavor property reference 57 | 7.4 Using sourceCompatibility 1.7 58 | 59 | ##Introduction 60 | 61 | **This documentation is for the Gradle plugin version 0.9. Earlier versions may differ due to non-compatible we are introducing before 1.0.** 62 | 63 | ###Goals of the new Build System 64 | 65 | The goals of the new build system are: 66 | 67 | * Make it easy to reuse code and resources 68 | * Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application 69 | * Make it easy to configure, extend and customize the build process 70 | * Good IDE integration 71 | 72 | ###Why Gradle? 73 | 74 | Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins. 75 | 76 | Here are some of its features that made us choose Gradle: 77 | 78 | * Domain Specific Language (DSL) to describe and manipulate the build logic 79 | * 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. 80 | * Built-in dependency management through Maven and/or Ivy. 81 | * Very flexible. Allows using best practices but doesn’t force its own way of doing things. 82 | * Plugins can expose their own DSL and their own API for build files to use. 83 | * Good Tooling API allowing IDE integration 84 | 85 | ##Requirements 86 | 87 | * Gradle 1.10 or 1.11 or 1.12 with the plugin 0.11.1 88 | * SDK with Build Tools 19.0.0. Some features may require a more recent version. 89 | 90 | ##Basic Project 91 | 92 | A Gradle project describes its build in a file called build.gradle located in the root folder of the project. 93 | 94 | ###Simple build files 95 | 96 | The most simple Java-only project has the following *build.gradle*: 97 | 98 | apply plugin: 'java' 99 | 100 | This applies the Java plugin, which is packaged with Gradle. The plugin provides everything to build and test Java applications. 101 | 102 | The most simple Android project has the following build.gradle: 103 | 104 | buildscript { 105 | repositories { 106 | mavenCentral() 107 | } 108 | 109 | dependencies { 110 | classpath 'com.android.tools.build:gradle:0.11.1' 111 | } 112 | } 113 | 114 | apply plugin: 'android' 115 | 116 | android { 117 | compileSdkVersion 19 118 | buildToolsVersion "19.0.0" 119 | } 120 | 121 | There are 3 main areas to this Android build file: 122 | 123 | `buildscript { ... }` configures the code driving the build. 124 | 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 125 | 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. 126 | 127 | Then, the `android` plugin is applied like the Java plugin earlier. 128 | 129 | Finally, `android { ... }` configures all the parameters for the android build. This is the entry point for the Android DSL. 130 | By default, only the compilation `target`, and the version of the build-tools are needed. This is done with the `compileSdkVersion` and `buildtoolsVersion` properties. 131 | 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. 132 | 133 | **Important:** You should only apply the `android` plugin. Applying the `java` plugin as well will result in a build error. 134 | 135 | **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. 136 | 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. 137 | 138 | ###Project Structure 139 | 140 | 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. 141 | 142 | The basic project starts with two components called “source sets”. The main source code and the test code. These live respectively in: 143 | 144 | * src/main/ 145 | * src/androidTest/ 146 | 147 | Inside each of these folders exists folder for each source components. 148 | 149 | For both the Java and Android plugin, the location of the Java source code and the Java resources: 150 | 151 | * java/ 152 | * resources/ 153 | 154 | For the Android plugin, extra files and folders specific to Android: 155 | 156 | * AndroidManifest.xml 157 | * res/ 158 | * assets/ 159 | * aidl/ 160 | * rs/ 161 | * jni/ 162 | 163 | Note: src/androidTest/AndroidManifest.xml is not needed as it is created automatically. 164 | 165 | ####Configuring the Structure 166 | 167 | 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: 168 | 169 | sourceSets { 170 | main { 171 | java { 172 | srcDir 'src/java' 173 | } 174 | resources { 175 | srcDir 'src/resources' 176 | } 177 | } 178 | } 179 | 180 | **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). 181 | 182 | 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: 183 | 184 | sourceSets { 185 | main.java.srcDirs = ['src/java'] 186 | main.resources.srcDirs = ['src/resources'] 187 | } 188 | 189 | For more information, see the Gradle documentation on the Java plugin [here](http://gradle.org/docs/current/userguide/java_plugin.html). 190 | 191 | The Android plugin uses a similar syntaxes, but because it uses its own sourceSets, this is done within the `android` object. 192 | Here’s an example, using the old project structure for the main code and remapping the `androidTest` sourceSet to the tests folder: 193 | 194 | android { 195 | sourceSets { 196 | main { 197 | manifest.srcFile 'AndroidManifest.xml' 198 | java.srcDirs = ['src'] 199 | resources.srcDirs = ['src'] 200 | aidl.srcDirs = ['src'] 201 | renderscript.srcDirs = ['src'] 202 | res.srcDirs = ['res'] 203 | assets.srcDirs = ['assets'] 204 | } 205 | 206 | androidTest.setRoot('tests') 207 | } 208 | } 209 | 210 | **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. 211 | 212 | **Note:** `setRoot()` moves the whole sourceSet (and its sub folders) to a new folder. This moves `src/androidTest/* to tests/*` 213 | This is Android specific and will not work on Java sourceSets. 214 | 215 | The ‘migrated’ sample shows this. 216 | 217 | ###Build Tasks 218 | 219 | ####General Tasks 220 | 221 | 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. 222 | The convention for tasks is the following: 223 | 224 | * `assemble` 225 | 226 | The task to assemble the output(s) of the project 227 | 228 | * `check` 229 | 230 | The task to run all the checks. 231 | 232 | * `build` 233 | 234 | This task does both assemble and check 235 | 236 | * `clean` 237 | 238 | This task cleans the output of the project 239 | 240 | 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. 241 | 242 | This allows you to always call the same task(s) no matter what the type of project is, or what plugins are applied. 243 | 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. 244 | 245 | From the command line you can get the high level task running the following command: 246 | 247 | gradle tasks 248 | 249 | For a full list and seeing dependencies between the tasks run: 250 | 251 | gradle tasks --all 252 | 253 | **Note:** Gradle automatically monitor the declared inputs and outputs of a task. 254 | 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. 255 | 256 | ####Java project tasks 257 | 258 | The Java plugin creates mainly two tasks, that are dependencies of the main anchor tasks: 259 | 260 | * `assemble` 261 | * `jar` 262 | 263 | This task creates the output. 264 | 265 | * `check` 266 | * `test` 267 | 268 | This task runs the tests. 269 | 270 | The jar task itself will depend directly and indirectly on other tasks: `classes` for instance will compile the Java code. 271 | The tests are compiled with `testClasses`, but it is rarely useful to call this as `test` depends on it (as well as `classes`). 272 | 273 | In general, you will probably only ever call `assemble` or `check`, and ignore the other tasks. 274 | 275 | You can see the full set of tasks and their descriptions for the Java plugin [here](http://gradle.org/docs/current/userguide/java_plugin.html). 276 | 277 | ####Android tasks 278 | 279 | The Android plugin use the same convention to stay compatible with other plugins, and adds an additional anchor task: 280 | 281 | * `assemble` 282 | 283 | The task to assemble the output(s) of the project 284 | 285 | * `check` 286 | 287 | The task to run all the checks. 288 | 289 | * `connectedCheck` 290 | 291 | Runs checks that requires a connected device or emulator. they will run on all connected devices in parallel. 292 | 293 | * `deviceCheck` 294 | 295 | Runs checks using APIs to connect to remote devices. This is used on CI servers. 296 | 297 | * `build` 298 | 299 | This task does both assemble and check 300 | 301 | * `clean` 302 | This task cleans the output of the project 303 | 304 | The new anchor tasks are necessary in order to be able to run regular checks without needing a connected device. 305 | Note that `build` does not depend on `deviceCheck`, or `connectedCheck`. 306 | 307 | 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: 308 | 309 | * `assemble` 310 | * `assembleDebug` 311 | * `assembleRelease` 312 | 313 | 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. 314 | 315 | **Tip:** Gradle support camel case shortcuts for task names on the command line. For instance: 316 | gradle aR 317 | is the same as typing 318 | gradle assembleRelease 319 | as long as no other task match ‘aR’ 320 | 321 | The check anchor tasks have their own dependencies: 322 | 323 | * `check` 324 | * `lint` 325 | * `connectedCheck` 326 | * `connectedAndroidTest` 327 | * `connectedUiAutomatorTest` (not implemented yet) 328 | * `deviceCheck` 329 | * This depends on tasks created when other plugins implement test extension points. 330 | 331 | Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing). 332 | 333 | ####Basic Build Customization 334 | 335 | The Android plugin provides a broad DSL to customize most things directly from the build system. 336 | 337 | ####Manifest entries 338 | 339 | Through the DSL it is possible to configure the following manifest entries: 340 | 341 | * minSdkVersion 342 | * targetSdkVersion 343 | * versionCode 344 | * versionName 345 | * packageName 346 | * Package Name for the test application 347 | * Instrumentation test runner 348 | 349 | **Example:** 350 | 351 | `android { 352 | compileSdkVersion 19 353 | buildToolsVersion "19.0.0" 354 | 355 | defaultConfig { 356 | versionCode 12 357 | versionName "2.0" 358 | minSdkVersion 16 359 | targetSdkVersion 16 360 | } 361 | }` 362 | 363 | The defaultConfig element inside the android element is where all this configuration is defined. 364 | 365 | Previous versions of the Android Plugin used packageName to configure the manifest 'packageName' attribute. 366 | Starting in 0.11.0, you should use applicationId in the build.gradle to configure the manifest 'packageName' entry. 367 | This was disambiguated to reduce confusion between the application's packageName (which is its ID) and 368 | java packages. 369 | 370 | The power of describing it in the build file is that it can be dynamic. 371 | For instance, one could be reading the version name from a file somewhere or using some custom logic: 372 | 373 | `def computeVersionName() { 374 | ... 375 | } 376 | 377 | android { 378 | compileSdkVersion 19 379 | buildToolsVersion "19.0.0" 380 | 381 | defaultConfig { 382 | versionCode 12 383 | versionName computeVersionName() 384 | minSdkVersion 16 385 | targetSdkVersion 16 386 | } 387 | }` 388 | 389 | **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. 390 | 391 | If a property is not set through the DSL, some default value will be used. Here’s a table of how this is processed. 392 | 393 | | Property Name | Default value in DSL object | Default values | 394 | |:----------|:-------------|:------------| 395 | | versionCode | -1 | value from manifest if present | 396 | | versionName | null | value from manifest if present | 397 | | minSdkVersion | -1 | value from manifest if present | 398 | | targetSdkVersion | -1 | value from manifest if present | 399 | | applicationId | null | value from manifest if present | 400 | | testApplicationId | null | applicationId + “.test” | 401 | | testInstrumentationRunner | null | android.test.InstrumentationTestRunner | 402 | | signingConfig | null | null | 403 | | proguardFile | N/A (set only) | N/A (set only) | 404 | | proguardFiles | N/A (set only) | N/A (set only) | 405 | 406 | 407 | 408 | 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: 409 | 410 | `if (android.defaultConfig.testInstrumentationRunner == null) { 411 | // assign a better default... 412 | }` 413 | 414 | 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. 415 | This is to prevent parsing the manifest of the application unless it’s really needed. 416 | 417 | ####Build Types 418 | 419 | By default, the Android plugin automatically sets up the project to build both a debug and a release version of the application. 420 | These differ mostly around the ability to debug the application on a secure (non dev) devices, and how the APK is signed. 421 | 422 | 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. 423 | 424 | This configuration is done through an object called a BuildType. By default, 2 instances are created, a debug and a release one. 425 | 426 | The Android plugin allows customizing those two instances as well as creating other Build Types. This is done with the buildTypes DSL container: 427 | 428 | `android { 429 | buildTypes { 430 | debug { 431 | applicationIdSuffix ".debug" 432 | } 433 | 434 | jnidebug.initWith(buildTypes.debug) 435 | jnidebug { 436 | packageNameSuffix ".jnidebug" 437 | jnidebugBuild true 438 | } 439 | } 440 | }` 441 | 442 | The above snippet achieves the following: 443 | Configures the default debug Build Type: 444 | set its package to be .debug to be able to install both debug and release apk on the same device 445 | Creates a new BuildType called jnidebug and configure it to be a copy of the debug build type. 446 | Keep configuring the jnidebug, by enabling debug build of the JNI component, and add a different package suffix. 447 | 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. 448 | 449 | The possible properties and their default values are: 450 | 451 | | Property Name | Default values for debug | Default values for release / other | 452 | |:----------|:-------------|:------------| 453 | | debuggable | true | false | 454 | | jniDebugBuild | false | false | 455 | | renderscriptDebugBuild | false | false | 456 | | renderscriptOptimLevel | 3 | 3 | 457 | | applicationIdSuffix | null | null | 458 | | versionNameSuffix | null | null | 459 | | signingConfig | android.signingConfigs.debug | null | 460 | | zipAlign | false | true | 461 | | runProguard | false | false | 462 | | proguardFile | N/A (set only) | N/A (set only) | 463 | | proguardFiles | N/A (set only) | N/A (set only) | 464 | 465 | 466 | In addition to these properties, Build Types can contribute to the build with code and resources. 467 | For each Build Type, a new matching sourceSet is created, with a default location of 468 | 469 | `src//` 470 | 471 | 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. 472 | 473 | Like any other source sets, the location of the build type source set can be relocated: 474 | 475 | `android { 476 | sourceSets.jnidebug.setRoot('foo/jnidebug') 477 | }` 478 | 479 | Additionally, for each Build Type, a new assemble task is created. 480 | 481 | 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. 482 | 483 | 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. 484 | 485 | Tip: remember that you can type `gradle` aJ to run the **assembleJnidebug** task. 486 | 487 | Possible use case: 488 | 489 | * Permissions in debug mode only, but not in release mode 490 | * Custom implementation for debugging 491 | * Different resources for debug mode (for instance when a resource value is tied to the signing certificate). 492 | 493 | The code/resources of the BuildType are used in the following way: 494 | 495 | * The manifest is merged into the app manifest 496 | * The code acts as just another source folder 497 | * The resources are overlayed over the main resources, replacing existing values. 498 | 499 | ####Signing Configurations 500 | 501 | Signing an application requires the following: 502 | 503 | * A keystore 504 | * A keystore password 505 | * A key alias name 506 | * A key password 507 | * The store type 508 | 509 | The location, as well as the key name, both passwords and store type form together a Signing Configuration (type SigningConfig) 510 | 511 | 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. 512 | The debug keystore is located in $HOME/.android/debug.keystore, and is created if not present. 513 | 514 | The debug Build Type is set to use this debug SigningConfig automatically. 515 | 516 | It is possible to create other configurations or customize the default built-in one. This is done through the signingConfigs DSL container: 517 | 518 | android { 519 | signingConfigs { 520 | debug { 521 | storeFile file("debug.keystore") 522 | } 523 | 524 | myConfig { 525 | storeFile file("other.keystore") 526 | storePassword "android" 527 | keyAlias "androiddebugkey" 528 | keyPassword "android" 529 | } 530 | } 531 | 532 | buildTypes { 533 | foo { 534 | debuggable true 535 | jniDebugBuild true 536 | signingConfig signingConfigs.myConfig 537 | } 538 | } 539 | } 540 | 541 | 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. 542 | 543 | It also creates a new Signing Config and a new Build Type that uses the new configuration. 544 | 545 | 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. 546 | 547 | 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). 548 | 549 | **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.** 550 | 551 | [http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle](http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle) 552 | 553 | **We'll update this guide with more detailed information later.** 554 | 555 | #####Running ProGuard 556 | 557 | 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. 558 | 559 | android { 560 | buildTypes { 561 | release { 562 | runProguard true 563 | proguardFile getDefaultProguardFile('proguard-android.txt') 564 | } 565 | } 566 | 567 | productFlavors { 568 | flavor1 { 569 | } 570 | flavor2 { 571 | proguardFile 'some-other-rules.txt' 572 | } 573 | } 574 | }` 575 | 576 | Variants use all the rules files declared in their build type, and product flavors. 577 | 578 | There are 2 default rules files 579 | 580 | * proguard-android.txt 581 | * proguard-android-optimize.txt 582 | 583 | They are located in the SDK. Using *getDefaultProguardFile()* will return the full path to the files. They are identical except for enabling optimizations. 584 | 585 | ##Dependencies, Android Libraries and Multi-project setup 586 | 587 | Gradle projects can have dependencies on other components. These components can be external binary packages, or other Gradle projects. 588 | 589 | ###Dependencies on binary packages 590 | 591 | ####Local packages 592 | 593 | To configure a dependency on an external library jar, you need to add a dependency on the compile configuration. 594 | 595 | dependencies { 596 | compile files('libs/foo.jar') 597 | } 598 | 599 | android { 600 | ... 601 | } 602 | 603 | Note: the dependencies DSL element is part of the standard Gradle API and does not belong inside the android element. 604 | 605 | 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. 606 | There are other possible configurations to add dependencies to: 607 | 608 | * compile: main application 609 | * androidTestCompile: test application 610 | * debugCompile: debug Build Type 611 | * releaseCompile: release Build Type. 612 | 613 | 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 `Compile`. 614 | 615 | Creating a new Build Type automatically creates a new configuration based on its name. 616 | 617 | 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. 618 | 619 | ####Remote artifacts 620 | 621 | Gradle supports pulling artifacts from Maven and Ivy repositories. 622 | 623 | 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. 624 | 625 | repositories { 626 | mavenCentral() 627 | } 628 | 629 | 630 | dependencies { 631 | compile 'com.google.guava:guava:11.0.2' 632 | } 633 | 634 | android { 635 | ... 636 | } 637 | 638 | **Note:** mavenCentral() is a shortcut to specifying the URL of the repository. Gradle supports both remote and local repositories. 639 | Note: Gradle will follow all dependencies transitively. This means that if a dependency has dependencies of its own, those are pulled in as well. 640 | 641 | For more information about setting up dependencies, read the Gradle user guide here, and DSL documentation here. 642 | 643 | ###Multi project setup 644 | 645 | Gradle projects can also depend on other gradle projects by using a multi-project setup. 646 | 647 | A multi-project setup usually works by having all the projects as sub folders of a given root project. 648 | 649 | For instance, given to following structure: 650 | 651 | MyProject/ 652 | + app/ 653 | + libraries/ 654 | + lib1/ 655 | + lib2/ 656 | 657 | We can identify 3 projects. Gradle will reference them with the following name: 658 | 659 | :app 660 | :libraries:lib1 661 | :libraries:lib2 662 | 663 | Each projects will have its own build.gradle declaring how it gets built. 664 | Additionally, there will be a file called settings.gradle at the root declaring the projects. 665 | This gives the following structure: 666 | 667 | MyProject/ 668 | | settings.gradle 669 | + app/ 670 | | build.gradle 671 | + libraries/ 672 | + lib1/ 673 | | build.gradle 674 | + lib2/ 675 | | build.gradle 676 | 677 | 678 | The content of settings.gradle is very simple: 679 | 680 | include ':app', ':libraries:lib1', ':libraries:lib2' 681 | 682 | This defines which folder is actually a Gradle project. 683 | 684 | The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies: 685 | 686 | dependencies { 687 | compile project(':libraries:lib1') 688 | } 689 | 690 | More general information about multi-project setup [here](http://gradle.org/docs/current/userguide/multi_project_builds.html). 691 | 692 | ###Library projects 693 | 694 | 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. 695 | 696 | 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. 697 | 698 | ####Creating a Library Project 699 | 700 | A Library project is very similar to a regular Android project with a few differences. 701 | 702 | 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 703 | com.android.tools.build.gradle jar. 704 | 705 | buildscript { 706 | repositories { 707 | mavenCentral() 708 | } 709 | 710 | dependencies { 711 | classpath 'com.android.tools.build:gradle:0.5.6' 712 | } 713 | } 714 | 715 | apply plugin: 'android-library' 716 | 717 | android { 718 | compileSdkVersion 15 719 | } 720 | 721 | 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. 722 | 723 | ####Differences between a Project and a Library Project 724 | 725 | 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). 726 | A library project can also generate a test apk to test the library independently from an application. 727 | 728 | The same anchor tasks are used for this (assembleDebug, assembleRelease) so there’s no 729 | difference in commands to build such a project. 730 | 731 | 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. 732 | 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. 733 | 734 | ####Referencing a Library 735 | 736 | Referencing a library is done the same way any other project is referenced: 737 | 738 | dependencies { 739 | compile project(':libraries:lib1') 740 | compile project(':libraries:lib2') 741 | } 742 | 743 | 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. 744 | 745 | ####Library Publication 746 | 747 | 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. 748 | 749 | You can control which variant gets published with 750 | 751 | android { 752 | defaultPublishConfig "debug" 753 | } 754 | 755 | 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: 756 | 757 | android { 758 | defaultPublishConfig "flavor1Debug" 759 | } 760 | 761 | 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). 762 | Publishing of all variants are not enabled by default. To enable them: 763 | 764 | android { 765 | publishNonDefault true 766 | } 767 | 768 | 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. 769 | 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. 770 | 771 | Gradle has a concept of default" artifact. This is the one that is used when writing: 772 | 773 | compile project(':libraries:lib2') 774 | 775 | To create a dependency on another published artifact, you need to specify which one to use: 776 | 777 | dependencies { 778 | flavor1Compile project(path: ':lib1', configuration: 'flavor1Release') 779 | flavor2Compile project(path: ':lib1', configuration: 'flavor2Release') 780 | } 781 | 782 | **Important:** Note that the published configuration is a full variant, including the build type, and needs to be referenced as such. 783 | 784 | **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. 785 | 786 | ##Testing 787 | 788 | Building a test application is integrated into the application project. There is no need for a separate test project anymore. 789 | 790 | ###Basics and Configuration 791 | 792 | As mentioned previously, next to the main sourceSet is the androidTest sourceSet, located by default in src/androidTest/ 793 | From this sourceSet is built a test apk that can be deployed to a device to test the application using the Android testing framework. This can contain unit tests, instrumentation tests, and later uiautomator tests. 794 | The sourceSet should not contain an AndroidManifest.xml as it is automatically generated. 795 | 796 | There are a few values that can be configured for the test app: 797 | 798 | * testPackageName 799 | * testInstrumentationRunner 800 | * testHandleProfiling 801 | * testFunctionalTest 802 | 803 | As seen previously, those are configured in the defaultConfig object: 804 | 805 | android { 806 | defaultConfig { 807 | testPackageName "com.test.foo" 808 | testInstrumentationRunner "android.test.InstrumentationTestRunner" 809 | testHandleProfiling true 810 | testFunctionalTest true 811 | } 812 | } 813 | 814 | 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 Type objects. This is one of the reason the manifest is generated automatically. 815 | 816 | Additionally, the sourceSet can be configured to have its own dependencies. 817 | By default, the application and its own dependencies are added to the test app classpath, but this can be extended with 818 | 819 | dependencies { 820 | androidTestCompile 'com.google.guava:guava:11.0.2' 821 | } 822 | 823 | 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. 824 | 825 | Currently only one Build Type is tested. By default it is the debug Build Type, but this can be reconfigured with: 826 | 827 | android { 828 | ... 829 | testBuildType "staging" 830 | } 831 | 832 | ###Running tests 833 | 834 | As mentioned previously, checks requiring a connected device are launched with the anchor task called connectedCheck. 835 | This depends on the task androidTest and therefore will run it. This task does the following: 836 | 837 | * Ensure the app and the test app are built (depending on assembleDebug and assembleTest) 838 | * Install both apps 839 | * Run the tests 840 | * Uninstall both apps. 841 | 842 | 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. 843 | 844 | All test results are stored as XML files under 845 | build/androidTest-results 846 | (This is similar to regular jUnit results that are stored under build/test-results) 847 | 848 | This can be configured with 849 | 850 | android { 851 | ... 852 | 853 | testOptions { 854 | resultsDir = "$project.buildDir/foo/results" 855 | } 856 | } 857 | 858 | The value of `android.testOptions.resultsDir` is evaluated with `Project.file(String)` 859 | 860 | ####esting Android Libraries 861 | 862 | Testing Android Library project is done exactly the same way as application projects. 863 | 864 | The only difference is that the whole library (and its dependencies) is automatically added as a Library dependency to the test app. The result is that the test APK includes not only its own code, but also the library itself and all its dependencies. 865 | The manifest of the Library is merged into the manifest of the test app (as is the case for any project referencing this Library). 866 | 867 | The `androidTest` task is changed to only install (and uninstall) the test APK (since there are no other APK to install.) 868 | 869 | Everything else is identical. 870 | 871 | ###Test reports 872 | 873 | When running unit tests, Gradle outputs an HTML report to easily look at the results. 874 | The Android plugins build on this and extends the HTML report to aggregate the results from all connected devices. 875 | 876 | ####Single projects 877 | 878 | The project is automatically generated upon running the tests. Its default location is 879 | 880 | build/reports/androidTests 881 | 882 | This is similar to the jUnit report location, which is build/reports/tests, or other reports usually located in build/reports// 883 | 884 | The location can be customized with 885 | 886 | android { 887 | ... 888 | 889 | testOptions { 890 | reportDir = "$project.buildDir/foo/report" 891 | } 892 | } 893 | 894 | The report will aggregate tests that ran on different devices. 895 | 896 | ####Multi-projects reports 897 | 898 | In 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. 899 | 900 | To do this, a different plugin is available in the same artifact. It can be applied with: 901 | 902 | buildscript { 903 | repositories { 904 | mavenCentral() 905 | } 906 | 907 | dependencies { 908 | classpath 'com.android.tools.build:gradle:0.5.6' 909 | } 910 | } 911 | 912 | apply plugin: 'android-reporting' 913 | 914 | This should be applied to the root project, ie in build.gradle next to settings.gradle 915 | 916 | Then from the root folder, the following command line will run all the tests and aggregate the reports: 917 | 918 | gradle deviceCheck mergeAndroidReports --continue 919 | 920 | 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. 921 | 922 | ###Lint support 923 | 924 | As 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. 925 | 926 | 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. 927 | 928 | android { 929 | lintOptions { 930 | // set to true to turn off analysis progress reporting by lint 931 | quiet true 932 | // if true, stop the gradle build if errors are found 933 | abortOnError false 934 | // if true, only report errors 935 | ignoreWarnings true 936 | // if true, emit full/absolute paths to files with errors (true by default) 937 | //absolutePaths true 938 | // if true, check all issues, including those that are off by default 939 | checkAllWarnings true 940 | // if true, treat all warnings as errors 941 | warningsAsErrors true 942 | // turn off checking the given issue id's 943 | disable 'TypographyFractions','TypographyQuotes' 944 | // turn on the given issue id's 945 | enable 'RtlHardcoded','RtlCompat', 'RtlEnabled' 946 | // check *only* the given issue id's 947 | check 'NewApi', 'InlinedApi' 948 | // if true, don't include source code lines in the error output 949 | noLines true 950 | // if true, show all locations for an error, do not truncate lists, etc. 951 | showAll true 952 | // Fallback lint configuration (default severities, etc.) 953 | lintConfig file("default-lint.xml") 954 | // if true, generate a text report of issues (false by default) 955 | textReport true 956 | // location to write the output; can be a file or 'stdout' 957 | textOutput 'stdout' 958 | // if true, generate an XML report for use by for example Jenkins 959 | xmlReport false 960 | // file to write report to (if not specified, defaults to lint-results.xml) 961 | xmlOutput file("lint-report.xml") 962 | // if true, generate an HTML report (with issue explanations, sourcecode, etc) 963 | htmlReport true 964 | // optional path to report (default will be lint-results.html in the builddir) 965 | htmlOutput file("lint-report.html") 966 | 967 | // set to true to have all release builds run lint on issues with severity=fatal 968 | // and abort the build (controlled by abortOnError above) if fatal issues are found 969 | checkReleaseBuilds true 970 | // Set the severity of the given issues to fatal (which means they will be 971 | // checked during release builds (even if the lint target is not included) 972 | fatal 'NewApi', 'InlineApi' 973 | // Set the severity of the given issues to error 974 | error 'Wakelock', 'TextViewEdits' 975 | // Set the severity of the given issues to warning 976 | warning 'ResourceAsColor' 977 | // Set the severity of the given issues to ignore (same as disabling the check) 978 | ignore 'TypographyQuotes' 979 | } 980 | } 981 | 982 | ##Build Variants 983 | 984 | One goal of the new build system is to enable creating different versions of the same application. 985 | 986 | There are two main use cases: 987 | 988 | 1. Different versions of the same application 989 | For instance, a free/demo version vs the “pro” paid application. 990 | 2. Same application packaged differently for multi-apk in Google Play Store. 991 | See http://developer.android.com/google/play/publishing/multiple-apks.html for more information. 992 | 3. A combination of 1. and 2. 993 | 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. 994 | 995 | ###Product flavors 996 | 997 | A 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. 998 | 999 | 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. 1000 | 1001 | Product flavors are declared using a productFlavors DSL container: 1002 | 1003 | android { 1004 | .... 1005 | 1006 | productFlavors { 1007 | flavor1 { 1008 | ... 1009 | } 1010 | 1011 | flavor2 { 1012 | ... 1013 | } 1014 | } 1015 | } 1016 | 1017 | This creates two flavors, called `flavor1` and `flavor2`. 1018 | Note: The name of the flavors cannot collide with existing Build Type names, or with the `androidTest` sourceSet. 1019 | 1020 | ###Build Type + Product Flavor = Build Variant 1021 | 1022 | As we have seen before, each Build Type generates a new APK. 1023 | 1024 | *Product Flavors* do the same: the output of the project becomes all possible combinations of *Build Types* and, if *applicable*, *Product Flavors*. 1025 | 1026 | Each (*Build Type, Product Flavor*) combination is called a Build Variant. 1027 | 1028 | For instance, with the default `debug` and `release` Build Types, the above example generates four Build Variants: 1029 | 1030 | * Flavor1 - debug 1031 | * Flavor1 - release 1032 | * Flavor2 - debug 1033 | * Flavor2 - release 1034 | 1035 | 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*. 1036 | Product Flavor Configuration 1037 | 1038 | Each flavors is configured with a closure: 1039 | 1040 | android { 1041 | ... 1042 | 1043 | defaultConfig { 1044 | minSdkVersion 8 1045 | versionCode 10 1046 | } 1047 | 1048 | productFlavors { 1049 | flavor1 { 1050 | packageName "com.example.flavor1" 1051 | versionCode 20 1052 | } 1053 | 1054 | flavor2 { 1055 | packageName "com.example.flavor2" 1056 | minSdkVersion 14 1057 | } 1058 | } 1059 | } 1060 | 1061 | Note that the `android.productFlavors.*` objects are of type ProductFlavor which is the same type as the `android.defaultConfig` object. This means they share the same properties. 1062 | 1063 | `defaultConfig` provides the base configuration for all flavors and each flavor can override any value. In the example above, the configurations end up being: 1064 | 1065 | * flavor1 1066 | * packageName: com.example.flavor1 1067 | * minSdkVersion: 8 1068 | * versionCode: 20 1069 | * flavor2 1070 | * packageName: com.example.flavor2 1071 | * minSdkVersion: 14 1072 | * versionCode: 10 1073 | 1074 | 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`. 1075 | 1076 | 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. 1077 | 1078 | For instance, `signingConfig` is one of these properties. 1079 | This enables either having all release packages share the same SigningConfig, by setting `android.buildTypes.release.signingConfig`, or have each release package use their own *SigningConfig* by setting each `android.productFlavors.*.signingConfig` objects separately. 1080 | 1081 | ###Sourcesets and Dependencies 1082 | 1083 | Similar to Build Types, Product Flavors also contribute code and resources through their own sourceSets. 1084 | 1085 | The above example creates four sourceSets: 1086 | 1087 | * android.sourceSets.flavor1 1088 | 1089 | Location src/flavor1/ 1090 | 1091 | * android.sourceSets.flavor2 1092 | 1093 | Location src/flavor2/ 1094 | 1095 | * android.sourceSets.androidTestFlavor1 1096 | 1097 | Location src/androidTestFlavor1/ 1098 | 1099 | * android.sourceSets.androidTestFlavor2 1100 | 1101 | Location src/androidTestFlavor2/ 1102 | 1103 | Those sourceSets are used to build the APK, alongside `android.sourceSets.main` and the Build Type sourceSet. 1104 | 1105 | The following rules are used when dealing with all the sourcesets used to build a single APK: 1106 | 1107 | * All source code (*src/\*/java*) are used together as multiple folders generating a single output. 1108 | * Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or permissions, similarly to Build Types. 1109 | * All resources (Android res and assets) are used using overlay priority where the Build Type overrides the Product Flavor, which overrides the main sourceSet. 1110 | * Each Build Variant generates its own R class (or other generated source code) from the resources. Nothing is shared between variants. 1111 | 1112 | 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. 1113 | 1114 | dependencies { 1115 | flavor1Compile "..." 1116 | } 1117 | 1118 | In this particular case, the file src/flavor1/AndroidManifest.xml would probably need to include the internet permission. 1119 | 1120 | Additional sourcesets are also created for each variants: 1121 | 1122 | * android.sourceSets.flavor1Debug 1123 | 1124 | Location src/flavor1Debug/ 1125 | 1126 | * android.sourceSets.flavor1Release 1127 | 1128 | Location src/flavor1Release/ 1129 | 1130 | * android.sourceSets.flavor2Debug 1131 | 1132 | Location src/flavor2Debug/ 1133 | 1134 | * android.sourceSets.flavor2Release 1135 | 1136 | Location src/flavor2Release/ 1137 | 1138 | These have higher priority than the build type `sourcesets`, and allow customization at the variant level. 1139 | 1140 | ###Building and Tasks 1141 | 1142 | We previously saw that each Build Type creates its own assemble task, but that Build Variants are a combination of Build Type and Product Flavor. 1143 | 1144 | When Product Flavors are used, more assemble-type tasks are created. These are: 1145 | 1146 | 1. assemble 1147 | 2. assemble 1148 | 3. assemble 1149 | 1150 | \#1 allows directly building a single variant. For instance `assembleFlavor1Debug`. 1151 | 1152 | \#2 allows building all APKs for a given Build Type. For instance `assembleDebug` will build both *Flavor1Debug* and *Flavor2Debug* variants. 1153 | 1154 | \#3 allows building all APKs for a given flavor. For instance `assembleFlavor1` will build both *Flavor1Debug* and *Flavor1Release* variants. 1155 | 1156 | The task assemble will build all possible variants. 1157 | 1158 | ###Testing 1159 | 1160 | Testing multi-flavors project is very similar to simpler projects. 1161 | 1162 | The `androidTest` sourceset is used for common tests across all flavors, while each flavor can also have its own tests. 1163 | 1164 | As mentioned above, sourceSets to test each flavor are created: 1165 | 1166 | * android.sourceSets.androidTestFlavor1 1167 | 1168 | Location src/androidTestFlavor1/ 1169 | 1170 | * android.sourceSets.androidTestFlavor2 1171 | 1172 | Location src/androidTestFlavor2/ 1173 | 1174 | Similarly, those can have their own dependencies: 1175 | 1176 | dependencies { 1177 | androidTestFlavor1Compile "..." 1178 | } 1179 | 1180 | 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. 1181 | 1182 | Each flavor has its own task to run tests: androidTest. For instance: 1183 | 1184 | * androidTestFlavor1Debug 1185 | * androidTestFlavor2Debug 1186 | 1187 | Similarly, test APK building tasks and install/uninstall tasks are per variant: 1188 | 1189 | * assembleFlavor1Test 1190 | * installFlavor1Debug 1191 | * installFlavor1Test 1192 | * uninstallFlavor1Debug 1193 | * ... 1194 | 1195 | Finally the HTML report generation supports aggregation by flavor. 1196 | The location of the test results and reports is as follows, first for the per flavor version, and then for the aggregated one: 1197 | 1198 | * build/androidTest-results/flavors/ 1199 | * build/androidTest-results/all/ 1200 | * build/reports/androidTests/flavors 1201 | * build/reports/androidTests/all/ 1202 | 1203 | Customizing either path, will only change the root folder and still create sub folders per-flavor and aggregated results/reports. 1204 | 1205 | ###Multi-flavor variants 1206 | 1207 | In some case, one may want to create several versions of the same apps based on more than one criteria. 1208 | 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. 1209 | 1210 | 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*). 1211 | 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. 1212 | Instead, there are two dimensions of flavors, and variants should automatically build all possible combinations. 1213 | 1214 | This feature is implemented using Flavor Groups. Each group represents a dimension, and flavors are assigned to a specific group. 1215 | 1216 | android { 1217 | ... 1218 | 1219 | flavorGroups "abi", "version" 1220 | 1221 | productFlavors { 1222 | freeapp { 1223 | flavorGroup "version" 1224 | ... 1225 | } 1226 | 1227 | x86 { 1228 | flavorGroup "abi" 1229 | ... 1230 | } 1231 | } 1232 | } 1233 | 1234 | The android.flavorGroups array defines the possible groups, as well as the order. Each defined Product Flavor is assigned to a group. 1235 | 1236 | From the following grouped Product Flavors [freeapp, paidapp] and [x86, arm, mips] and the [debug, release] Build Types, the following build variants will be created: 1237 | 1238 | * x86-freeapp-debug 1239 | * x86-freeapp-release 1240 | * arm-freeapp-debug 1241 | * arm-freeapp-release 1242 | * mips-freeapp-debug 1243 | * mips-freeapp-release 1244 | * x86-paidapp-debug 1245 | * x86-paidapp-release 1246 | * arm-paidapp-debug 1247 | * arm-paidapp-release 1248 | * mips-paidapp-debug 1249 | * mips-paidapp-release 1250 | 1251 | The order of the group as defined by `android.flavorGroups` is very important. 1252 | 1253 | Each variant is configured by several Product Flavor objects: 1254 | 1255 | * `android.defaultConfig` 1256 | * One from the abi group 1257 | * One from the version group 1258 | 1259 | 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. 1260 | The flavor groups is defined with higher priority first. So in this case: 1261 | 1262 | abi > version > defaultConfig 1263 | 1264 | Multi-flavors projects also have additional sourcesets, similar to the variant sourcesets but without the build type: 1265 | 1266 | * android.sourceSets.x86Freeapp 1267 | 1268 | Location src/x86Freeapp/ 1269 | 1270 | * android.sourceSets.armPaidapp 1271 | 1272 | Location src/armPaidapp/ 1273 | 1274 | * etc... 1275 | 1276 | 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. 1277 | 1278 | ##Advanced Build Customization 1279 | 1280 | ###Build options 1281 | 1282 | ####Java Compilation options 1283 | 1284 | android { 1285 | compileOptions { 1286 | sourceCompatibility = "1.6" 1287 | targetCompatibility = "1.6" 1288 | } 1289 | } 1290 | 1291 | Default value is “1.6”. This affect all tasks compiling Java source code. 1292 | 1293 | ####aapt options 1294 | 1295 | android { 1296 | aaptOptions { 1297 | noCompress 'foo', 'bar' 1298 | ignoreAssetsPattern "!.svn:!.git:!.ds_store:!\*.scc:.\*:_\*:!CVS:!thumbs.db:!picasa.ini:!\*~" 1299 | } 1300 | } 1301 | 1302 | This affects all tasks using aapt. 1303 | 1304 | ####dex options 1305 | 1306 | android { 1307 | dexOptions { 1308 | incremental false 1309 | preDexLibraries = false 1310 | jumboMode = false 1311 | } 1312 | } 1313 | 1314 | This affects all tasks using dex. 1315 | 1316 | ###Manipulating tasks 1317 | 1318 | Basic Java projects have a finite set of tasks that all work together to create an output. 1319 | The classes task is the one that compile the Java source code. 1320 | It’s easy to access from *build.gradle* by simply using `classes` in a script. This is a shortcut for `project.tasks.classes`. 1321 | 1322 | 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*. 1323 | 1324 | In order to fix this, the `android` object has two properties: 1325 | 1326 | * applicationVariants (only for the app plugin) 1327 | * libraryVariants (only for the library plugin) 1328 | * testVariants (for both plugins) 1329 | 1330 | All three return a [DomainObjectCollection](http://www.gradle.org/docs/current/javadoc/org/gradle/api/DomainObjectCollection.html) of *ApplicationVariant*, *LibraryVariant*, and *TestVariant*```` objects respectively. 1331 | 1332 | 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. 1333 | 1334 | The DomainObjectCollection gives access to all the objects directly, or through filters which can be convenient. 1335 | 1336 | android.applicationVariants.each { variant -> 1337 | .... 1338 | } 1339 | 1340 | All three variant classes share the following properties: 1341 | 1342 | | Property Name | Property Type | Description | 1343 | |:----------|:-------------|:------|:----------| 1344 | | name | String | The name of the variant. Guaranteed to be unique. | 1345 | | description | String | Human readable description of the variant. | 1346 | | dirName | String | subfolder name for the variant. Guaranteed to be unique. Maybe more than one folder, ie “debug/flavor1” | 1347 | | baseName | String | Base name of the output(s) of the variant. Guaranteed to be unique. | 1348 | | outputFile | File | The output of the variant. This is a read/write property | 1349 | processManifest | ProcessManifest | The task that processes the manifest. | 1350 | | aidlCompile | AidlCompile | The task that compiles the AIDL files. | 1351 | | renderscriptCompile | RenderscriptCompile | The task that compiles the Renderscript files. | 1352 | | mergeResources | MergeResources | The task that merges the resources. | 1353 | | mergeAssets | MergeAssets | The task that merges the assets. | 1354 | | processResources | ProcessAndroidResources | The task that processes and compile the Resources. | 1355 | | generateBuildConfig | GenerateBuildConfig | The task that generates the BuildConfig class. | 1356 | | javaCompile | JavaCompile | The task that compiles the Java code. | 1357 | | processJavaResources | Copy | The task that process the Java resources. | 1358 | | assemble | DefaultTask | The assemble anchor task for this variant. | 1359 | 1360 | **The** *ApplicationVariant* class adds the following: 1361 | 1362 | | Property Name | Property Type | Description | 1363 | |:----------|:-------------|:------|:----------| 1364 | | buildType | BuildType | The BuildType of the variant. | 1365 | | productFlavors | List | The ProductFlavors of the variant. Always non Null but could be empty. | 1366 | | mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors | 1367 | | signingConfig | SigningConfig | The SigningConfig object used by this variant | 1368 | | isSigningReady | boolean | true if the variant has all the information needed to be signed. | 1369 | | testedVariant | BaseVariant | The BaseVariant that is tested by this TestVariant. | 1370 | | dex | Dex | The task that dex the code. Can be null if the variant is a library. | 1371 | | packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. | 1372 | | zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. | 1373 | | install | DefaultTask | The installation task. Can be null. | 1374 | | uninstall | DefaultTask | The uninstallation task. | 1375 | 1376 | **The** *LibraryVariant* class adds the following: 1377 | 1378 | | Property Name | Property Type | Description | 1379 | |:----------|:-------------|:------|:----------| 1380 | | buildType | BuildType | The BuildType of the variant.| 1381 | | mergedFlavor | ProductFlavor | The defaultConfig values| 1382 | | testVariant | BuildVariant | The Build Variant that will test this variant. | 1383 | | packageLibrary | Zip | The task that packages the Library AAR archive. | Null if not a library.| 1384 | 1385 | **The** *TestVariant* class adds the following: 1386 | 1387 | | Property Name | Property Type | Description | 1388 | |:----------|:-------------|:------|:----------| 1389 | | buildType | BuildType | The BuildType of the variant.| 1390 | | productFlavors | List | The ProductFlavors of the variant. Always non Null but could be empty. | 1391 | | mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors | 1392 | | signingConfig | SigningConfig | The SigningConfig object used by this variant | 1393 | | isSigningReady | boolean | true if the variant has all the information needed to be signed. | 1394 | | testedVariant | BaseVariant | The BaseVariant that is tested by this TestVariant. | 1395 | | dex | Dex | The task that dex the code. Can be null if the variant is a library. | 1396 | | packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. | 1397 | | zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. | 1398 | | install | DefaultTask | The installation task. Can be null. | 1399 | | uninstall | DefaultTask | The uninstallation task. | 1400 | | connectedAndroidTest | DefaultTask | The task that runs the android tests on connected devices. 1401 | | providerAndroidTest | DefaultTask | The task that runs the android tests using the extension API. 1402 | 1403 | 1404 | API for Android specific task types. 1405 | 1406 | * ProcessManifest 1407 | * File manifestOutputFile 1408 | * AidlCompile 1409 | * File sourceOutputDir 1410 | * RenderscriptCompile 1411 | * File sourceOutputDir 1412 | * File resOutputDir 1413 | * MergeResources 1414 | * File outputDir 1415 | * MergeAssets 1416 | * File outputDir 1417 | * ProcessAndroidResources 1418 | * File manifestFile 1419 | * File resDir 1420 | * File assetsDir 1421 | * File sourceOutputDir 1422 | * File textSymbolOutputDir 1423 | * File packageOutputFile 1424 | * File proguardOutputFile 1425 | * GenerateBuildConfig 1426 | * File sourceOutputDir 1427 | * Dex 1428 | * File outputFolder 1429 | * PackageApplication 1430 | * File resourceFile 1431 | * File dexFile 1432 | * File javaResourceDir 1433 | * File jniDir 1434 | * File outputFile 1435 | * To change the final output file use "outputFile" on the variant object directly. 1436 | * ZipAlign 1437 | * File inputFile 1438 | * File outputFile 1439 | * To change the final output file use "outputFile" on the variant object directly. 1440 | 1441 | The API for each task type is limited due to both how Gradle works and how the Android plugin sets them up. 1442 | 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. 1443 | 1444 | 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. 1445 | 1446 | 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. 1447 | 1448 | 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. 1449 | 1450 | For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation. 1451 | 1452 | ###BuildType and Product Flavor property reference 1453 | 1454 | coming soon. 1455 | For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation. 1456 | 1457 | ###Using sourceCompatibility 1.7 1458 | 1459 | 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: 1460 | 1461 | android { 1462 | compileSdkVersion 19 1463 | buildToolsVersion "19.0.0" 1464 | 1465 | defaultConfig { 1466 | minSdkVersion 7 1467 | targetSdkVersion 19 1468 | } 1469 | 1470 | compileOptions { 1471 | sourceCompatibility JavaVersion.VERSION_1_7 1472 | targetCompatibility JavaVersion.VERSION_1_7 1473 | } 1474 | } 1475 | 1476 | Note that you can use `minSdkVersion` with 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 `minSdkVersion` of 19. 1477 | 1478 | 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.) 1479 | 1480 | --- 1481 | 1482 | 原文地址:[http://tools.android.com/tech-docs/new-build-system/user-guide](http://tools.android.com/tech-docs/new-build-system/user-guide) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Gradle Plugin User Guide 中文版 2 | =========================== 3 | 4 | 5 | 目录 6 | 7 | 1. [**引言**](https://github.com/inferjay/GradlePluginUserGuideCN#引言) 8 | 9 | 1.1. [新构建系统的目标](https://github.com/inferjay/GradlePluginUserGuideCN#新构建系统的目标) 10 | 11 | 1.2. [为什么用Gradle?](https://github.com/inferjay/GradlePluginUserGuideCN#为什么用gradle) 12 | 2. [**要求**](https://github.com/inferjay/GradlePluginUserGuideCN#要求) 13 | 3. [**基本项目**](https://github.com/inferjay/GradlePluginUserGuideCN#基本项目) 14 | 15 | 3.1 [简单的构建文件](https://github.com/inferjay/GradlePluginUserGuideCN#简单的构建文件) 16 | 17 | 3.2 [项目结构](https://github.com/inferjay/GradlePluginUserGuideCN#项目结构) 18 | 19 | 3.2.1 [配置项目结构](https://github.com/inferjay/GradlePluginUserGuideCN#项目结构配置) 20 | 21 | 3.3 [构建任务](https://github.com/inferjay/GradlePluginUserGuideCN#构建任务) 22 | 23 | 3.3.1 [普通构建任务](https://github.com/inferjay/GradlePluginUserGuideCN#普通构建任务) 24 | 25 | 3.3.2 [Java项目构建任务](https://github.com/inferjay/GradlePluginUserGuideCN#java项目构建任务) 26 | 27 | 3.3.3 [Android项目构建任务](https://github.com/inferjay/GradlePluginUserGuideCN#android项目构建任务) 28 | 29 | 3.4 [基本构建定制](https://github.com/inferjay/GradlePluginUserGuideCN#基本构建定制) 30 | 31 | 3.4.1 [Manifest entries](https://github.com/inferjay/GradlePluginUserGuideCN#manifest-entries) 32 | 33 | 3.4.2 [构建类型](https://github.com/inferjay/GradlePluginUserGuideCN#构建类型) 34 | 35 | 3.4.3 [签名配置](https://github.com/inferjay/GradlePluginUserGuideCN#签名配置) 36 | 37 | 3.4.4 [运行ProGuard](https://github.com/inferjay/GradlePluginUserGuideCN#运行proguard) 38 | 39 | 4. [**依赖, Android库和多项目设置**](https://github.com/inferjay/GradlePluginUserGuideCN#依赖-android库和多项目设置) 40 | 41 | 4.1 [依赖二进制包](https://github.com/inferjay/GradlePluginUserGuideCN#依赖二进制包) 42 | 43 | 4.1.1 [本地包](https://github.com/inferjay/GradlePluginUserGuideCN#本地包) 44 | 45 | 4.1.2 [远程包](https://github.com/inferjay/GradlePluginUserGuideCN#远程包) 46 | 47 | 4.2 [多项目设置](https://github.com/inferjay/GradlePluginUserGuideCN#多项目设置) 48 | 49 | 4.3 [Library项目](https://github.com/inferjay/GradlePluginUserGuideCN#library项目) 50 | 51 | 4.3.1 [创建一个Library项目](https://github.com/inferjay/GradlePluginUserGuideCN#创建一个library项目) 52 | 53 | 4.3.2 [项目和Library项目之间的差异](https://github.com/inferjay/GradlePluginUserGuideCN#项目和library项目之间的差异) 54 | 55 | 4.3.3 [引用一个Library](https://github.com/inferjay/GradlePluginUserGuideCN#引用一个library) 56 | 57 | 4.3.4 [Library的发布](https://github.com/inferjay/GradlePluginUserGuideCN#library的发布) 58 | 59 | 5. [**测试**](https://github.com/inferjay/GradlePluginUserGuideCN#测试) 60 | 61 | 5.1 [测试的基本信息和配置](https://github.com/inferjay/GradlePluginUserGuideCN#测试的基本信息和配置) 62 | 63 | 5.2 [运行测试](https://github.com/inferjay/GradlePluginUserGuideCN#运行测试) 64 | 65 | 5.3 [测试Android Libraries](https://github.com/inferjay/GradlePluginUserGuideCN#测试android-libraries) 66 | 67 | 5.4 [测试报告](https://github.com/inferjay/GradlePluginUserGuideCN#测试报告) 68 | 69 | 5.4.1 [单个项目的测试报告](https://github.com/inferjay/GradlePluginUserGuideCN#单个项目的测试报告) 70 | 71 | 5.4.2 [多个项目的测试报告](https://github.com/inferjay/GradlePluginUserGuideCN#多项目的测试报告) 72 | 73 | 5.5 [Lint支持](https://github.com/inferjay/GradlePluginUserGuideCN#lint支持) 74 | 75 | 6. [**构建变体**](https://github.com/inferjay/GradlePluginUserGuideCN#构建变体) 76 | 77 | 6.1 [Product flavors](https://github.com/inferjay/GradlePluginUserGuideCN#product-flavors) 78 | 79 | 6.2 [构建类型 + Product Flavor = 构建变体](https://github.com/inferjay/GradlePluginUserGuideCN#构建类型--product-flavor--构建变体) 80 | 81 | 6.3 [Product Flavor配置](https://github.com/inferjay/GradlePluginUserGuideCN#Product-Flavor配置) 82 | 83 | 6.4 [源码集合和依赖](https://github.com/inferjay/GradlePluginUserGuideCN#源码集合和依赖) 84 | 85 | 6.5 [构建和任务](https://github.com/inferjay/GradlePluginUserGuideCN#构建和任务) 86 | 87 | 6.6 [测试Multi-flavor项目](https://github.com/inferjay/GradlePluginUserGuideCN#测试multi-flavors项目) 88 | 89 | 6.7 [Multi-flavo变体](https://github.com/inferjay/GradlePluginUserGuideCN#multi-flavor变体) 90 | 91 | 7. [**高级构建定制**](https://github.com/inferjay/GradlePluginUserGuideCN#高级构建定制) 92 | 93 | 7.1 [构建选项](https://github.com/inferjay/GradlePluginUserGuideCN#构建选项) 94 | 95 | 7.1.1 [Java编译选项](https://github.com/inferjay/GradlePluginUserGuideCN#java编译选项) 96 | 97 | 7.1.2 [aapt选项](https://github.com/inferjay/GradlePluginUserGuideCN#aapt选项) 98 | 99 | 7.1.3 [dex选项](https://github.com/inferjay/GradlePluginUserGuideCN#dex选项) 100 | 101 | 7.2 [操纵构建任务](https://github.com/inferjay/GradlePluginUserGuideCN#操纵构建任务) 102 | 103 | 7.3 [构建类型和Product Flavor属性引用](https://github.com/inferjay/GradlePluginUserGuideCN#构建类型和product-flavor属性引用) 104 | 105 | 7.4 [使用sourceCompatibility 1.7](https://github.com/inferjay/GradlePluginUserGuideCN#使用sourcecompatibility-17) 106 | 107 | 108 | ## 引言 109 | 110 | **This documentation is for the Gradle plugin version 0.9. Earlier versions may differ due to non-compatible we are introducing before 1.0.** 111 | 112 | ### 新构建系统的目标 113 | 114 | The goals of the new build system are: 115 | 116 | * Make it easy to reuse code and resources 117 | * Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application 118 | * Make it easy to configure, extend and customize the build process 119 | * Good IDE integration 120 | 121 | ### 为什么用Gradle? 122 | 123 | Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins. 124 | 125 | Here are some of its features that made us choose Gradle: 126 | 127 | * Domain Specific Language (DSL) to describe and manipulate the build logic 128 | * 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. 129 | * Built-in dependency management through Maven and/or Ivy. 130 | * Very flexible. Allows using best practices but doesn’t force its own way of doing things. 131 | * Plugins can expose their own DSL and their own API for build files to use. 132 | * Good Tooling API allowing IDE integration 133 | 134 | ## 要求 135 | 136 | * Gradle 1.10 or 1.11 or 1.12 with the plugin 0.11.1 137 | * SDK with Build Tools 19.0.0. Some features may require a more recent version. 138 | 139 | ## 基本项目 140 | 141 | A Gradle project describes its build in a file called build.gradle located in the root folder of the project. 142 | 143 | ### 简单的构建文件 144 | 145 | The most simple Java-only project has the following *build.gradle*: 146 | 147 | apply plugin: 'java' 148 | 149 | This applies the Java plugin, which is packaged with Gradle. The plugin provides everything to build and test Java applications. 150 | 151 | The most simple Android project has the following build.gradle: 152 | 153 | buildscript { 154 | repositories { 155 | mavenCentral() 156 | } 157 | 158 | dependencies { 159 | classpath 'com.android.tools.build:gradle:0.11.1' 160 | } 161 | } 162 | 163 | apply plugin: 'android' 164 | 165 | android { 166 | compileSdkVersion 19 167 | buildToolsVersion "19.0.0" 168 | } 169 | 170 | There are 3 main areas to this Android build file: 171 | 172 | `buildscript { ... }` configures the code driving the build. 173 | 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 174 | 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. 175 | 176 | Then, the `android` plugin is applied like the Java plugin earlier. 177 | 178 | Finally, `android { ... }` configures all the parameters for the android build. This is the entry point for the Android DSL. 179 | By default, only the compilation `target`, and the version of the build-tools are needed. This is done with the `compileSdkVersion` and `buildtoolsVersion` properties. 180 | 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. 181 | 182 | **Important:** You should only apply the `android` plugin. Applying the `java` plugin as well will result in a build error. 183 | 184 | **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. 185 | 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. 186 | 187 | ### 项目结构 188 | 189 | 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. 190 | 191 | The basic project starts with two components called “source sets”. The main source code and the test code. These live respectively in: 192 | 193 | * src/main/ 194 | * src/androidTest/ 195 | 196 | Inside each of these folders exists folder for each source components. 197 | 198 | For both the Java and Android plugin, the location of the Java source code and the Java resources: 199 | 200 | * java/ 201 | * resources/ 202 | 203 | For the Android plugin, extra files and folders specific to Android: 204 | 205 | * AndroidManifest.xml 206 | * res/ 207 | * assets/ 208 | * aidl/ 209 | * rs/ 210 | * jni/ 211 | 212 | Note: src/androidTest/AndroidManifest.xml is not needed as it is created automatically. 213 | 214 | #### 项目结构配置 215 | 216 | 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: 217 | 218 | sourceSets { 219 | main { 220 | java { 221 | srcDir 'src/java' 222 | } 223 | resources { 224 | srcDir 'src/resources' 225 | } 226 | } 227 | } 228 | 229 | **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). 230 | 231 | 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: 232 | 233 | sourceSets { 234 | main.java.srcDirs = ['src/java'] 235 | main.resources.srcDirs = ['src/resources'] 236 | } 237 | 238 | For more information, see the Gradle documentation on the Java plugin [here](http://gradle.org/docs/current/userguide/java_plugin.html). 239 | 240 | The Android plugin uses a similar syntaxes, but because it uses its own sourceSets, this is done within the `android` object. 241 | Here’s an example, using the old project structure for the main code and remapping the `androidTest` sourceSet to the tests folder: 242 | 243 | android { 244 | sourceSets { 245 | main { 246 | manifest.srcFile 'AndroidManifest.xml' 247 | java.srcDirs = ['src'] 248 | resources.srcDirs = ['src'] 249 | aidl.srcDirs = ['src'] 250 | renderscript.srcDirs = ['src'] 251 | res.srcDirs = ['res'] 252 | assets.srcDirs = ['assets'] 253 | } 254 | 255 | androidTest.setRoot('tests') 256 | } 257 | } 258 | 259 | **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. 260 | 261 | **Note:** `setRoot()` moves the whole sourceSet (and its sub folders) to a new folder. This moves `src/androidTest/* to tests/*` 262 | This is Android specific and will not work on Java sourceSets. 263 | 264 | The ‘migrated’ sample shows this. 265 | 266 | ### 构建任务 267 | 268 | #### 普通构建任务 269 | 270 | 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. 271 | The convention for tasks is the following: 272 | 273 | * `assemble` 274 | 275 | The task to assemble the output(s) of the project 276 | 277 | * `check` 278 | 279 | The task to run all the checks. 280 | 281 | * `build` 282 | 283 | This task does both assemble and check 284 | 285 | * `clean` 286 | 287 | This task cleans the output of the project 288 | 289 | 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. 290 | 291 | This allows you to always call the same task(s) no matter what the type of project is, or what plugins are applied. 292 | 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. 293 | 294 | From the command line you can get the high level task running the following command: 295 | 296 | gradle tasks 297 | 298 | For a full list and seeing dependencies between the tasks run: 299 | 300 | gradle tasks --all 301 | 302 | **Note:** Gradle automatically monitor the declared inputs and outputs of a task. 303 | 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. 304 | 305 | #### Java项目构建任务 306 | 307 | The Java plugin creates mainly two tasks, that are dependencies of the main anchor tasks: 308 | 309 | * `assemble` 310 | * `jar` 311 | 312 | This task creates the output. 313 | 314 | * `check` 315 | * `test` 316 | 317 | This task runs the tests. 318 | 319 | The jar task itself will depend directly and indirectly on other tasks: `classes` for instance will compile the Java code. 320 | The tests are compiled with `testClasses`, but it is rarely useful to call this as `test` depends on it (as well as `classes`). 321 | 322 | In general, you will probably only ever call `assemble` or `check`, and ignore the other tasks. 323 | 324 | You can see the full set of tasks and their descriptions for the Java plugin [here](http://gradle.org/docs/current/userguide/java_plugin.html). 325 | 326 | #### Android项目构建任务 327 | 328 | The Android plugin use the same convention to stay compatible with other plugins, and adds an additional anchor task: 329 | 330 | * `assemble` 331 | 332 | The task to assemble the output(s) of the project 333 | 334 | * `check` 335 | 336 | The task to run all the checks. 337 | 338 | * `connectedCheck` 339 | 340 | Runs checks that requires a connected device or emulator. they will run on all connected devices in parallel. 341 | 342 | * `deviceCheck` 343 | 344 | Runs checks using APIs to connect to remote devices. This is used on CI servers. 345 | 346 | * `build` 347 | 348 | This task does both assemble and check 349 | 350 | * `clean` 351 | This task cleans the output of the project 352 | 353 | The new anchor tasks are necessary in order to be able to run regular checks without needing a connected device. 354 | Note that `build` does not depend on `deviceCheck`, or `connectedCheck`. 355 | 356 | 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: 357 | 358 | * `assemble` 359 | * `assembleDebug` 360 | * `assembleRelease` 361 | 362 | 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. 363 | 364 | **Tip:** Gradle support camel case shortcuts for task names on the command line. For instance: 365 | gradle aR 366 | is the same as typing 367 | gradle assembleRelease 368 | as long as no other task match ‘aR’ 369 | 370 | The check anchor tasks have their own dependencies: 371 | 372 | * `check` 373 | * `lint` 374 | * `connectedCheck` 375 | * `connectedAndroidTest` 376 | * `connectedUiAutomatorTest` (not implemented yet) 377 | * `deviceCheck` 378 | * This depends on tasks created when other plugins implement test extension points. 379 | 380 | Finally, the plugin creates install/uninstall tasks for all build types (debug, release, test), as long as they can be installed (which requires signing). 381 | 382 | #### 基本构建定制 383 | 384 | The Android plugin provides a broad DSL to customize most things directly from the build system. 385 | 386 | #### Manifest entries 387 | 388 | Through the DSL it is possible to configure the following manifest entries: 389 | 390 | * minSdkVersion 391 | * targetSdkVersion 392 | * versionCode 393 | * versionName 394 | * packageName 395 | * Package Name for the test application 396 | * Instrumentation test runner 397 | 398 | **Example:** 399 | 400 | `android { 401 | compileSdkVersion 19 402 | buildToolsVersion "19.0.0" 403 | 404 | defaultConfig { 405 | versionCode 12 406 | versionName "2.0" 407 | minSdkVersion 16 408 | targetSdkVersion 16 409 | } 410 | }` 411 | 412 | The defaultConfig element inside the android element is where all this configuration is defined. 413 | 414 | Previous versions of the Android Plugin used packageName to configure the manifest 'packageName' attribute. 415 | Starting in 0.11.0, you should use applicationId in the build.gradle to configure the manifest 'packageName' entry. 416 | This was disambiguated to reduce confusion between the application's packageName (which is its ID) and 417 | java packages. 418 | 419 | The power of describing it in the build file is that it can be dynamic. 420 | For instance, one could be reading the version name from a file somewhere or using some custom logic: 421 | 422 | `def computeVersionName() { 423 | ... 424 | } 425 | 426 | android { 427 | compileSdkVersion 19 428 | buildToolsVersion "19.0.0" 429 | 430 | defaultConfig { 431 | versionCode 12 432 | versionName computeVersionName() 433 | minSdkVersion 16 434 | targetSdkVersion 16 435 | } 436 | }` 437 | 438 | **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. 439 | 440 | If a property is not set through the DSL, some default value will be used. Here’s a table of how this is processed. 441 | 442 | | Property Name | Default value in DSL object | Default values | 443 | |:----------|:-------------|:------------| 444 | | versionCode | -1 | value from manifest if present | 445 | | versionName | null | value from manifest if present | 446 | | minSdkVersion | -1 | value from manifest if present | 447 | | targetSdkVersion | -1 | value from manifest if present | 448 | | applicationId | null | value from manifest if present | 449 | | testApplicationId | null | applicationId + “.test” | 450 | | testInstrumentationRunner | null | android.test.InstrumentationTestRunner | 451 | | signingConfig | null | null | 452 | | proguardFile | N/A (set only) | N/A (set only) | 453 | | proguardFiles | N/A (set only) | N/A (set only) | 454 | 455 | 456 | 457 | 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: 458 | 459 | `if (android.defaultConfig.testInstrumentationRunner == null) { 460 | // assign a better default... 461 | }` 462 | 463 | 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. 464 | This is to prevent parsing the manifest of the application unless it’s really needed. 465 | 466 | #### 构建类型 467 | 468 | By default, the Android plugin automatically sets up the project to build both a debug and a release version of the application. 469 | These differ mostly around the ability to debug the application on a secure (non dev) devices, and how the APK is signed. 470 | 471 | 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. 472 | 473 | This configuration is done through an object called a BuildType. By default, 2 instances are created, a debug and a release one. 474 | 475 | The Android plugin allows customizing those two instances as well as creating other Build Types. This is done with the buildTypes DSL container: 476 | 477 | `android { 478 | buildTypes { 479 | debug { 480 | applicationIdSuffix ".debug" 481 | } 482 | 483 | jnidebug.initWith(buildTypes.debug) 484 | jnidebug { 485 | packageNameSuffix ".jnidebug" 486 | jnidebugBuild true 487 | } 488 | } 489 | }` 490 | 491 | The above snippet achieves the following: 492 | Configures the default debug Build Type: 493 | set its package to be .debug to be able to install both debug and release apk on the same device 494 | Creates a new BuildType called jnidebug and configure it to be a copy of the debug build type. 495 | Keep configuring the jnidebug, by enabling debug build of the JNI component, and add a different package suffix. 496 | 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. 497 | 498 | The possible properties and their default values are: 499 | 500 | | Property Name | Default values for debug | Default values for release / other | 501 | |:----------|:-------------|:------------| 502 | | debuggable | true | false | 503 | | jniDebugBuild | false | false | 504 | | renderscriptDebugBuild | false | false | 505 | | renderscriptOptimLevel | 3 | 3 | 506 | | applicationIdSuffix | null | null | 507 | | versionNameSuffix | null | null | 508 | | signingConfig | android.signingConfigs.debug | null | 509 | | zipAlign | false | true | 510 | | runProguard | false | false | 511 | | proguardFile | N/A (set only) | N/A (set only) | 512 | | proguardFiles | N/A (set only) | N/A (set only) | 513 | 514 | 515 | In addition to these properties, Build Types can contribute to the build with code and resources. 516 | For each Build Type, a new matching sourceSet is created, with a default location of 517 | 518 | `src//` 519 | 520 | 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. 521 | 522 | Like any other source sets, the location of the build type source set can be relocated: 523 | 524 | `android { 525 | sourceSets.jnidebug.setRoot('foo/jnidebug') 526 | }` 527 | 528 | Additionally, for each Build Type, a new assemble task is created. 529 | 530 | 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. 531 | 532 | 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. 533 | 534 | Tip: remember that you can type `gradle` aJ to run the **assembleJnidebug** task. 535 | 536 | Possible use case: 537 | 538 | * Permissions in debug mode only, but not in release mode 539 | * Custom implementation for debugging 540 | * Different resources for debug mode (for instance when a resource value is tied to the signing certificate). 541 | 542 | The code/resources of the BuildType are used in the following way: 543 | 544 | * The manifest is merged into the app manifest 545 | * The code acts as just another source folder 546 | * The resources are overlayed over the main resources, replacing existing values. 547 | 548 | #### 签名配置 549 | 550 | Signing an application requires the following: 551 | 552 | * A keystore 553 | * A keystore password 554 | * A key alias name 555 | * A key password 556 | * The store type 557 | 558 | The location, as well as the key name, both passwords and store type form together a Signing Configuration (type SigningConfig) 559 | 560 | 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. 561 | The debug keystore is located in $HOME/.android/debug.keystore, and is created if not present. 562 | 563 | The debug Build Type is set to use this debug SigningConfig automatically. 564 | 565 | It is possible to create other configurations or customize the default built-in one. This is done through the signingConfigs DSL container: 566 | 567 | android { 568 | signingConfigs { 569 | debug { 570 | storeFile file("debug.keystore") 571 | } 572 | 573 | myConfig { 574 | storeFile file("other.keystore") 575 | storePassword "android" 576 | keyAlias "androiddebugkey" 577 | keyPassword "android" 578 | } 579 | } 580 | 581 | buildTypes { 582 | foo { 583 | debuggable true 584 | jniDebugBuild true 585 | signingConfig signingConfigs.myConfig 586 | } 587 | } 588 | } 589 | 590 | 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. 591 | 592 | It also creates a new Signing Config and a new Build Type that uses the new configuration. 593 | 594 | 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. 595 | 596 | 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). 597 | 598 | **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.** 599 | 600 | [http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle](http://stackoverflow.com/questions/18328730/how-to-create-a-release-signed-apk-file-using-gradle) 601 | 602 | **We'll update this guide with more detailed information later.** 603 | 604 | ##### 运行ProGuard 605 | 606 | 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. 607 | 608 | android { 609 | buildTypes { 610 | release { 611 | runProguard true 612 | proguardFile getDefaultProguardFile('proguard-android.txt') 613 | } 614 | } 615 | 616 | productFlavors { 617 | flavor1 { 618 | } 619 | flavor2 { 620 | proguardFile 'some-other-rules.txt' 621 | } 622 | } 623 | }` 624 | 625 | Variants use all the rules files declared in their build type, and product flavors. 626 | 627 | There are 2 default rules files 628 | 629 | * proguard-android.txt 630 | * proguard-android-optimize.txt 631 | 632 | They are located in the SDK. Using *getDefaultProguardFile()* will return the full path to the files. They are identical except for enabling optimizations. 633 | 634 | ## 依赖, Android库和多项目设置 635 | 636 | Gradle projects can have dependencies on other components. These components can be external binary packages, or other Gradle projects. 637 | 638 | ### 依赖二进制包 639 | 640 | #### 本地包 641 | 642 | To configure a dependency on an external library jar, you need to add a dependency on the compile configuration. 643 | 644 | dependencies { 645 | compile files('libs/foo.jar') 646 | } 647 | 648 | android { 649 | ... 650 | } 651 | 652 | Note: the dependencies DSL element is part of the standard Gradle API and does not belong inside the android element. 653 | 654 | 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. 655 | There are other possible configurations to add dependencies to: 656 | 657 | * compile: main application 658 | * androidTestCompile: test application 659 | * debugCompile: debug Build Type 660 | * releaseCompile: release Build Type. 661 | 662 | 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 `Compile`. 663 | 664 | Creating a new Build Type automatically creates a new configuration based on its name. 665 | 666 | 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. 667 | 668 | #### 远程包 669 | 670 | Gradle supports pulling artifacts from Maven and Ivy repositories. 671 | 672 | 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. 673 | 674 | repositories { 675 | mavenCentral() 676 | } 677 | 678 | 679 | dependencies { 680 | compile 'com.google.guava:guava:11.0.2' 681 | } 682 | 683 | android { 684 | ... 685 | } 686 | 687 | **Note:** mavenCentral() is a shortcut to specifying the URL of the repository. Gradle supports both remote and local repositories. 688 | Note: Gradle will follow all dependencies transitively. This means that if a dependency has dependencies of its own, those are pulled in as well. 689 | 690 | For more information about setting up dependencies, read the Gradle user guide here, and DSL documentation here. 691 | 692 | ### 多项目设置 693 | Gradle projects can also depend on other gradle projects by using a multi-project setup. 694 | 695 | A multi-project setup usually works by having all the projects as sub folders of a given root project. 696 | 697 | For instance, given to following structure: 698 | 699 | MyProject/ 700 | + app/ 701 | + libraries/ 702 | + lib1/ 703 | + lib2/ 704 | 705 | We can identify 3 projects. Gradle will reference them with the following name: 706 | 707 | :app 708 | :libraries:lib1 709 | :libraries:lib2 710 | 711 | Each projects will have its own build.gradle declaring how it gets built. 712 | Additionally, there will be a file called settings.gradle at the root declaring the projects. 713 | This gives the following structure: 714 | 715 | MyProject/ 716 | | settings.gradle 717 | + app/ 718 | | build.gradle 719 | + libraries/ 720 | + lib1/ 721 | | build.gradle 722 | + lib2/ 723 | | build.gradle 724 | 725 | 726 | The content of settings.gradle is very simple: 727 | 728 | include ':app', ':libraries:lib1', ':libraries:lib2' 729 | 730 | This defines which folder is actually a Gradle project. 731 | 732 | The :app project is likely to depend on the libraries, and this is done by declaring the following dependencies: 733 | 734 | dependencies { 735 | compile project(':libraries:lib1') 736 | } 737 | 738 | More general information about multi-project setup [here](http://gradle.org/docs/current/userguide/multi_project_builds.html). 739 | 740 | ### Library项目 741 | 742 | 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. 743 | 744 | 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. 745 | 746 | #### 创建一个Library项目 747 | 748 | A Library project is very similar to a regular Android project with a few differences. 749 | 750 | 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 751 | com.android.tools.build.gradle jar. 752 | 753 | buildscript { 754 | repositories { 755 | mavenCentral() 756 | } 757 | 758 | dependencies { 759 | classpath 'com.android.tools.build:gradle:0.5.6' 760 | } 761 | } 762 | 763 | apply plugin: 'android-library' 764 | 765 | android { 766 | compileSdkVersion 15 767 | } 768 | 769 | 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. 770 | 771 | #### 项目和Library项目之间的差异 772 | 773 | 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). 774 | A library project can also generate a test apk to test the library independently from an application. 775 | 776 | The same anchor tasks are used for this (assembleDebug, assembleRelease) so there’s no 777 | difference in commands to build such a project. 778 | 779 | 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. 780 | 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. 781 | 782 | #### 引用一个Library 783 | 784 | Referencing a library is done the same way any other project is referenced: 785 | 786 | dependencies { 787 | compile project(':libraries:lib1') 788 | compile project(':libraries:lib2') 789 | } 790 | 791 | 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. 792 | 793 | #### Library的发布 794 | 795 | 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. 796 | 797 | You can control which variant gets published with 798 | 799 | android { 800 | defaultPublishConfig "debug" 801 | } 802 | 803 | 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: 804 | 805 | android { 806 | defaultPublishConfig "flavor1Debug" 807 | } 808 | 809 | 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). 810 | Publishing of all variants are not enabled by default. To enable them: 811 | 812 | android { 813 | publishNonDefault true 814 | } 815 | 816 | 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. 817 | 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. 818 | 819 | Gradle has a concept of default" artifact. This is the one that is used when writing: 820 | 821 | compile project(':libraries:lib2') 822 | 823 | To create a dependency on another published artifact, you need to specify which one to use: 824 | 825 | dependencies { 826 | flavor1Compile project(path: ':lib1', configuration: 'flavor1Release') 827 | flavor2Compile project(path: ':lib1', configuration: 'flavor2Release') 828 | } 829 | 830 | **Important:** Note that the published configuration is a full variant, including the build type, and needs to be referenced as such. 831 | 832 | **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. 833 | 834 | ## 测试 835 | 836 | Building a test application is integrated into the application project. There is no need for a separate test project anymore. 837 | 838 | ### 测试的基本信息和配置 839 | 840 | As mentioned previously, next to the main sourceSet is the androidTest sourceSet, located by default in src/androidTest/ 841 | From this sourceSet is built a test apk that can be deployed to a device to test the application using the Android testing framework. This can contain unit tests, instrumentation tests, and later uiautomator tests. 842 | The sourceSet should not contain an AndroidManifest.xml as it is automatically generated. 843 | 844 | There are a few values that can be configured for the test app: 845 | 846 | * testPackageName 847 | * testInstrumentationRunner 848 | * testHandleProfiling 849 | * testFunctionalTest 850 | 851 | As seen previously, those are configured in the defaultConfig object: 852 | 853 | android { 854 | defaultConfig { 855 | testPackageName "com.test.foo" 856 | testInstrumentationRunner "android.test.InstrumentationTestRunner" 857 | testHandleProfiling true 858 | testFunctionalTest true 859 | } 860 | } 861 | 862 | 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 Type objects. This is one of the reason the manifest is generated automatically. 863 | 864 | Additionally, the sourceSet can be configured to have its own dependencies. 865 | By default, the application and its own dependencies are added to the test app classpath, but this can be extended with 866 | 867 | dependencies { 868 | androidTestCompile 'com.google.guava:guava:11.0.2' 869 | } 870 | 871 | 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. 872 | 873 | Currently only one Build Type is tested. By default it is the debug Build Type, but this can be reconfigured with: 874 | 875 | android { 876 | ... 877 | testBuildType "staging" 878 | } 879 | 880 | ### 运行测试 881 | 882 | As mentioned previously, checks requiring a connected device are launched with the anchor task called connectedCheck. 883 | This depends on the task androidTest and therefore will run it. This task does the following: 884 | 885 | * Ensure the app and the test app are built (depending on assembleDebug and assembleTest) 886 | * Install both apps 887 | * Run the tests 888 | * Uninstall both apps. 889 | 890 | 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. 891 | 892 | All test results are stored as XML files under 893 | build/androidTest-results 894 | (This is similar to regular jUnit results that are stored under build/test-results) 895 | 896 | This can be configured with 897 | 898 | android { 899 | ... 900 | 901 | testOptions { 902 | resultsDir = "$project.buildDir/foo/results" 903 | } 904 | } 905 | 906 | The value of `android.testOptions.resultsDir` is evaluated with `Project.file(String)` 907 | 908 | #### 测试Android Libraries 909 | 910 | Testing Android Library project is done exactly the same way as application projects. 911 | 912 | The only difference is that the whole library (and its dependencies) is automatically added as a Library dependency to the test app. The result is that the test APK includes not only its own code, but also the library itself and all its dependencies. 913 | The manifest of the Library is merged into the manifest of the test app (as is the case for any project referencing this Library). 914 | 915 | The `androidTest` task is changed to only install (and uninstall) the test APK (since there are no other APK to install.) 916 | 917 | Everything else is identical. 918 | 919 | ### 测试报告 920 | 921 | When running unit tests, Gradle outputs an HTML report to easily look at the results. 922 | The Android plugins build on this and extends the HTML report to aggregate the results from all connected devices. 923 | 924 | #### 单个项目的测试报告 925 | 926 | The project is automatically generated upon running the tests. Its default location is 927 | 928 | build/reports/androidTests 929 | 930 | This is similar to the jUnit report location, which is build/reports/tests, or other reports usually located in build/reports// 931 | 932 | The location can be customized with 933 | 934 | android { 935 | ... 936 | 937 | testOptions { 938 | reportDir = "$project.buildDir/foo/report" 939 | } 940 | } 941 | 942 | The report will aggregate tests that ran on different devices. 943 | 944 | #### 多项目的测试报告 945 | 946 | In 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. 947 | 948 | To do this, a different plugin is available in the same artifact. It can be applied with: 949 | 950 | buildscript { 951 | repositories { 952 | mavenCentral() 953 | } 954 | 955 | dependencies { 956 | classpath 'com.android.tools.build:gradle:0.5.6' 957 | } 958 | } 959 | 960 | apply plugin: 'android-reporting' 961 | 962 | This should be applied to the root project, ie in build.gradle next to settings.gradle 963 | 964 | Then from the root folder, the following command line will run all the tests and aggregate the reports: 965 | 966 | gradle deviceCheck mergeAndroidReports --continue 967 | 968 | 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. 969 | 970 | ### Lint支持 971 | 972 | As 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. 973 | 974 | 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. 975 | 976 | android { 977 | lintOptions { 978 | // set to true to turn off analysis progress reporting by lint 979 | quiet true 980 | // if true, stop the gradle build if errors are found 981 | abortOnError false 982 | // if true, only report errors 983 | ignoreWarnings true 984 | // if true, emit full/absolute paths to files with errors (true by default) 985 | //absolutePaths true 986 | // if true, check all issues, including those that are off by default 987 | checkAllWarnings true 988 | // if true, treat all warnings as errors 989 | warningsAsErrors true 990 | // turn off checking the given issue id's 991 | disable 'TypographyFractions','TypographyQuotes' 992 | // turn on the given issue id's 993 | enable 'RtlHardcoded','RtlCompat', 'RtlEnabled' 994 | // check *only* the given issue id's 995 | check 'NewApi', 'InlinedApi' 996 | // if true, don't include source code lines in the error output 997 | noLines true 998 | // if true, show all locations for an error, do not truncate lists, etc. 999 | showAll true 1000 | // Fallback lint configuration (default severities, etc.) 1001 | lintConfig file("default-lint.xml") 1002 | // if true, generate a text report of issues (false by default) 1003 | textReport true 1004 | // location to write the output; can be a file or 'stdout' 1005 | textOutput 'stdout' 1006 | // if true, generate an XML report for use by for example Jenkins 1007 | xmlReport false 1008 | // file to write report to (if not specified, defaults to lint-results.xml) 1009 | xmlOutput file("lint-report.xml") 1010 | // if true, generate an HTML report (with issue explanations, sourcecode, etc) 1011 | htmlReport true 1012 | // optional path to report (default will be lint-results.html in the builddir) 1013 | htmlOutput file("lint-report.html") 1014 | 1015 | // set to true to have all release builds run lint on issues with severity=fatal 1016 | // and abort the build (controlled by abortOnError above) if fatal issues are found 1017 | checkReleaseBuilds true 1018 | // Set the severity of the given issues to fatal (which means they will be 1019 | // checked during release builds (even if the lint target is not included) 1020 | fatal 'NewApi', 'InlineApi' 1021 | // Set the severity of the given issues to error 1022 | error 'Wakelock', 'TextViewEdits' 1023 | // Set the severity of the given issues to warning 1024 | warning 'ResourceAsColor' 1025 | // Set the severity of the given issues to ignore (same as disabling the check) 1026 | ignore 'TypographyQuotes' 1027 | } 1028 | } 1029 | 1030 | ## 构建变体 1031 | 1032 | One goal of the new build system is to enable creating different versions of the same application. 1033 | 1034 | There are two main use cases: 1035 | 1036 | 1. Different versions of the same application 1037 | For instance, a free/demo version vs the “pro” paid application. 1038 | 2. Same application packaged differently for multi-apk in Google Play Store. 1039 | See http://developer.android.com/google/play/publishing/multiple-apks.html for more information. 1040 | 3. A combination of 1. and 2. 1041 | 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. 1042 | 1043 | ### Product flavors 1044 | 1045 | A 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. 1046 | 1047 | 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. 1048 | 1049 | Product flavors are declared using a productFlavors DSL container: 1050 | 1051 | android { 1052 | .... 1053 | 1054 | productFlavors { 1055 | flavor1 { 1056 | ... 1057 | } 1058 | 1059 | flavor2 { 1060 | ... 1061 | } 1062 | } 1063 | } 1064 | 1065 | This creates two flavors, called `flavor1` and `flavor2`. 1066 | Note: The name of the flavors cannot collide with existing Build Type names, or with the `androidTest` sourceSet. 1067 | 1068 | ### 构建类型 + Product Flavor = 构建变体 1069 | 1070 | As we have seen before, each Build Type generates a new APK. 1071 | 1072 | *Product Flavors* do the same: the output of the project becomes all possible combinations of *Build Types* and, if *applicable*, *Product Flavors*. 1073 | 1074 | Each (*Build Type, Product Flavor*) combination is called a Build Variant. 1075 | 1076 | For instance, with the default `debug` and `release` Build Types, the above example generates four Build Variants: 1077 | 1078 | * Flavor1 - debug 1079 | * Flavor1 - release 1080 | * Flavor2 - debug 1081 | * Flavor2 - release 1082 | 1083 | 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*. 1084 | 1085 | ### Product Flavor配置 1086 | 1087 | Each flavors is configured with a closure: 1088 | 1089 | android { 1090 | ... 1091 | 1092 | defaultConfig { 1093 | minSdkVersion 8 1094 | versionCode 10 1095 | } 1096 | 1097 | productFlavors { 1098 | flavor1 { 1099 | packageName "com.example.flavor1" 1100 | versionCode 20 1101 | } 1102 | 1103 | flavor2 { 1104 | packageName "com.example.flavor2" 1105 | minSdkVersion 14 1106 | } 1107 | } 1108 | } 1109 | 1110 | Note that the `android.productFlavors.*` objects are of type ProductFlavor which is the same type as the `android.defaultConfig` object. This means they share the same properties. 1111 | 1112 | `defaultConfig` provides the base configuration for all flavors and each flavor can override any value. In the example above, the configurations end up being: 1113 | 1114 | * flavor1 1115 | * packageName: com.example.flavor1 1116 | * minSdkVersion: 8 1117 | * versionCode: 20 1118 | * flavor2 1119 | * packageName: com.example.flavor2 1120 | * minSdkVersion: 14 1121 | * versionCode: 10 1122 | 1123 | 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`. 1124 | 1125 | 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. 1126 | 1127 | For instance, `signingConfig` is one of these properties. 1128 | This enables either having all release packages share the same SigningConfig, by setting `android.buildTypes.release.signingConfig`, or have each release package use their own *SigningConfig* by setting each `android.productFlavors.*.signingConfig` objects separately. 1129 | 1130 | ### 源码集合和依赖 1131 | 1132 | Similar to Build Types, Product Flavors also contribute code and resources through their own sourceSets. 1133 | 1134 | The above example creates four sourceSets: 1135 | 1136 | * android.sourceSets.flavor1 1137 | 1138 | Location src/flavor1/ 1139 | 1140 | * android.sourceSets.flavor2 1141 | 1142 | Location src/flavor2/ 1143 | 1144 | * android.sourceSets.androidTestFlavor1 1145 | 1146 | Location src/androidTestFlavor1/ 1147 | 1148 | * android.sourceSets.androidTestFlavor2 1149 | 1150 | Location src/androidTestFlavor2/ 1151 | 1152 | Those sourceSets are used to build the APK, alongside `android.sourceSets.main` and the Build Type sourceSet. 1153 | 1154 | The following rules are used when dealing with all the sourcesets used to build a single APK: 1155 | 1156 | * All source code (*src/\*/java*) are used together as multiple folders generating a single output. 1157 | * Manifests are all merged together into a single manifest. This allows Product Flavors to have different components and/or permissions, similarly to Build Types. 1158 | * All resources (Android res and assets) are used using overlay priority where the Build Type overrides the Product Flavor, which overrides the main sourceSet. 1159 | * Each Build Variant generates its own R class (or other generated source code) from the resources. Nothing is shared between variants. 1160 | 1161 | 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. 1162 | 1163 | dependencies { 1164 | flavor1Compile "..." 1165 | } 1166 | 1167 | In this particular case, the file src/flavor1/AndroidManifest.xml would probably need to include the internet permission. 1168 | 1169 | Additional sourcesets are also created for each variants: 1170 | 1171 | * android.sourceSets.flavor1Debug 1172 | 1173 | Location src/flavor1Debug/ 1174 | 1175 | * android.sourceSets.flavor1Release 1176 | 1177 | Location src/flavor1Release/ 1178 | 1179 | * android.sourceSets.flavor2Debug 1180 | 1181 | Location src/flavor2Debug/ 1182 | 1183 | * android.sourceSets.flavor2Release 1184 | 1185 | Location src/flavor2Release/ 1186 | 1187 | These have higher priority than the build type `sourcesets`, and allow customization at the variant level. 1188 | 1189 | ### 构建和任务 1190 | 1191 | We previously saw that each Build Type creates its own assemble task, but that Build Variants are a combination of Build Type and Product Flavor. 1192 | 1193 | When Product Flavors are used, more assemble-type tasks are created. These are: 1194 | 1195 | 1. assemble 1196 | 2. assemble 1197 | 3. assemble 1198 | 1199 | \#1 allows directly building a single variant. For instance `assembleFlavor1Debug`. 1200 | 1201 | \#2 allows building all APKs for a given Build Type. For instance `assembleDebug` will build both *Flavor1Debug* and *Flavor2Debug* variants. 1202 | 1203 | \#3 allows building all APKs for a given flavor. For instance `assembleFlavor1` will build both *Flavor1Debug* and *Flavor1Release* variants. 1204 | 1205 | The task assemble will build all possible variants. 1206 | 1207 | ### 测试Multi-flavors项目 1208 | 1209 | Testing multi-flavors project is very similar to simpler projects. 1210 | 1211 | The `androidTest` sourceset is used for common tests across all flavors, while each flavor can also have its own tests. 1212 | 1213 | As mentioned above, sourceSets to test each flavor are created: 1214 | 1215 | * android.sourceSets.androidTestFlavor1 1216 | 1217 | Location src/androidTestFlavor1/ 1218 | 1219 | * android.sourceSets.androidTestFlavor2 1220 | 1221 | Location src/androidTestFlavor2/ 1222 | 1223 | Similarly, those can have their own dependencies: 1224 | 1225 | dependencies { 1226 | androidTestFlavor1Compile "..." 1227 | } 1228 | 1229 | 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. 1230 | 1231 | Each flavor has its own task to run tests: androidTest. For instance: 1232 | 1233 | * androidTestFlavor1Debug 1234 | * androidTestFlavor2Debug 1235 | 1236 | Similarly, test APK building tasks and install/uninstall tasks are per variant: 1237 | 1238 | * assembleFlavor1Test 1239 | * installFlavor1Debug 1240 | * installFlavor1Test 1241 | * uninstallFlavor1Debug 1242 | * ... 1243 | 1244 | Finally the HTML report generation supports aggregation by flavor. 1245 | The location of the test results and reports is as follows, first for the per flavor version, and then for the aggregated one: 1246 | 1247 | * build/androidTest-results/flavors/ 1248 | * build/androidTest-results/all/ 1249 | * build/reports/androidTests/flavors 1250 | * build/reports/androidTests/all/ 1251 | 1252 | Customizing either path, will only change the root folder and still create sub folders per-flavor and aggregated results/reports. 1253 | 1254 | ### Multi-flavor变体 1255 | 1256 | In some case, one may want to create several versions of the same apps based on more than one criteria. 1257 | 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. 1258 | 1259 | 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*). 1260 | 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. 1261 | Instead, there are two dimensions of flavors, and variants should automatically build all possible combinations. 1262 | 1263 | This feature is implemented using Flavor Groups. Each group represents a dimension, and flavors are assigned to a specific group. 1264 | 1265 | android { 1266 | ... 1267 | 1268 | flavorGroups "abi", "version" 1269 | 1270 | productFlavors { 1271 | freeapp { 1272 | flavorGroup "version" 1273 | ... 1274 | } 1275 | 1276 | x86 { 1277 | flavorGroup "abi" 1278 | ... 1279 | } 1280 | } 1281 | } 1282 | 1283 | The android.flavorGroups array defines the possible groups, as well as the order. Each defined Product Flavor is assigned to a group. 1284 | 1285 | From the following grouped Product Flavors [freeapp, paidapp] and [x86, arm, mips] and the [debug, release] Build Types, the following build variants will be created: 1286 | 1287 | * x86-freeapp-debug 1288 | * x86-freeapp-release 1289 | * arm-freeapp-debug 1290 | * arm-freeapp-release 1291 | * mips-freeapp-debug 1292 | * mips-freeapp-release 1293 | * x86-paidapp-debug 1294 | * x86-paidapp-release 1295 | * arm-paidapp-debug 1296 | * arm-paidapp-release 1297 | * mips-paidapp-debug 1298 | * mips-paidapp-release 1299 | 1300 | The order of the group as defined by `android.flavorGroups` is very important. 1301 | 1302 | Each variant is configured by several Product Flavor objects: 1303 | 1304 | * `android.defaultConfig` 1305 | * One from the abi group 1306 | * One from the version group 1307 | 1308 | 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. 1309 | The flavor groups is defined with higher priority first. So in this case: 1310 | 1311 | abi > version > defaultConfig 1312 | 1313 | Multi-flavors projects also have additional sourcesets, similar to the variant sourcesets but without the build type: 1314 | 1315 | * android.sourceSets.x86Freeapp 1316 | 1317 | Location src/x86Freeapp/ 1318 | 1319 | * android.sourceSets.armPaidapp 1320 | 1321 | Location src/armPaidapp/ 1322 | 1323 | * etc... 1324 | 1325 | 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. 1326 | 1327 | ## 高级构建定制 1328 | 1329 | ### 构建选项 1330 | 1331 | #### Java编译选项 1332 | 1333 | android { 1334 | compileOptions { 1335 | sourceCompatibility = "1.6" 1336 | targetCompatibility = "1.6" 1337 | } 1338 | } 1339 | 1340 | Default value is “1.6”. This affect all tasks compiling Java source code. 1341 | 1342 | #### aapt选项 1343 | 1344 | android { 1345 | aaptOptions { 1346 | noCompress 'foo', 'bar' 1347 | ignoreAssetsPattern "!.svn:!.git:!.ds_store:!\*.scc:.\*:_\*:!CVS:!thumbs.db:!picasa.ini:!\*~" 1348 | } 1349 | } 1350 | 1351 | This affects all tasks using aapt. 1352 | 1353 | #### dex选项 1354 | 1355 | android { 1356 | dexOptions { 1357 | incremental false 1358 | preDexLibraries = false 1359 | jumboMode = false 1360 | } 1361 | } 1362 | 1363 | This affects all tasks using dex. 1364 | 1365 | ### 操纵构建任务 1366 | 1367 | Basic Java projects have a finite set of tasks that all work together to create an output. 1368 | The classes task is the one that compile the Java source code. 1369 | It’s easy to access from *build.gradle* by simply using `classes` in a script. This is a shortcut for `project.tasks.classes`. 1370 | 1371 | 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*. 1372 | 1373 | In order to fix this, the `android` object has two properties: 1374 | 1375 | * applicationVariants (only for the app plugin) 1376 | * libraryVariants (only for the library plugin) 1377 | * testVariants (for both plugins) 1378 | 1379 | All three return a [DomainObjectCollection](http://www.gradle.org/docs/current/javadoc/org/gradle/api/DomainObjectCollection.html) of *ApplicationVariant*, *LibraryVariant*, and *TestVariant*```` objects respectively. 1380 | 1381 | 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. 1382 | 1383 | The DomainObjectCollection gives access to all the objects directly, or through filters which can be convenient. 1384 | 1385 | android.applicationVariants.each { variant -> 1386 | .... 1387 | } 1388 | 1389 | All three variant classes share the following properties: 1390 | 1391 | | Property Name | Property Type | Description | 1392 | | ------------ | ------------- | ------------- | 1393 | | name | String | The name of the variant. Guaranteed to be unique. | 1394 | | description | String | Human readable description of the variant. | 1395 | | dirName | String | subfolder name for the variant. Guaranteed to be unique. Maybe more than one folder, ie “debug/flavor1” | 1396 | | baseName | String | Base name of the output(s) of the variant. Guaranteed to be unique. | 1397 | | outputFile | File | The output of the variant. This is a read/write property | 1398 | processManifest | ProcessManifest | The task that processes the manifest. | 1399 | | aidlCompile | AidlCompile | The task that compiles the AIDL files. | 1400 | | renderscriptCompile | RenderscriptCompile | The task that compiles the Renderscript files. | 1401 | | mergeResources | MergeResources | The task that merges the resources. | 1402 | | mergeAssets | MergeAssets | The task that merges the assets. | 1403 | | processResources | ProcessAndroidResources | The task that processes and compile the Resources. | 1404 | | generateBuildConfig | GenerateBuildConfig | The task that generates the BuildConfig class. | 1405 | | javaCompile | JavaCompile | The task that compiles the Java code. | 1406 | | processJavaResources | Copy | The task that process the Java resources. | 1407 | | assemble | DefaultTask | The assemble anchor task for this variant. | 1408 | 1409 | **The** *ApplicationVariant* class adds the following: 1410 | 1411 | | Property Name | Property Type | Description | 1412 | | ------------ | ------------- | ------------- | 1413 | | buildType | BuildType | The BuildType of the variant. | 1414 | | productFlavors | List | The ProductFlavors of the variant. Always non Null but could be empty. | 1415 | | mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors | 1416 | | signingConfig | SigningConfig | The SigningConfig object used by this variant | 1417 | | isSigningReady | boolean | true if the variant has all the information needed to be signed. | 1418 | | testedVariant | BaseVariant | The BaseVariant that is tested by this TestVariant. | 1419 | | dex | Dex | The task that dex the code. Can be null if the variant is a library. | 1420 | | packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. | 1421 | | zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. | 1422 | | install | DefaultTask | The installation task. Can be null. | 1423 | | uninstall | DefaultTask | The uninstallation task. | 1424 | 1425 | **The** *LibraryVariant* class adds the following: 1426 | 1427 | | Property Name | Property Type | Description | 1428 | | ------------ | ------------- | ------------- | 1429 | | buildType | BuildType | The BuildType of the variant. | 1430 | | mergedFlavor | ProductFlavor | The defaultConfig values | 1431 | | testVariant | BuildVariant | The Build Variant that will test this variant. | 1432 | | packageLibrary | Zip | The task that packages the Library AAR archive. | Null if not a library. | 1433 | 1434 | **The** *TestVariant* class adds the following: 1435 | 1436 | | Property Name | Property Type | Description | 1437 | | ------------ | ------------- | ------------- | 1438 | | buildType | BuildType | The BuildType of the variant. | 1439 | | productFlavors | List | The ProductFlavors of the variant. Always non Null but could be empty. | 1440 | | mergedFlavor | ProductFlavor | The merging of android.defaultConfig and variant.productFlavors | 1441 | | signingConfig | SigningConfig | The SigningConfig object used by this variant | 1442 | | isSigningReady | boolean | true if the variant has all the information needed to be signed. | 1443 | | testedVariant | BaseVariant | The BaseVariant that is tested by this TestVariant. | 1444 | | dex | Dex | The task that dex the code. Can be null if the variant is a library. | 1445 | | packageApplication | PackageApplication | The task that makes the final APK. Can be null if the variant is a library. | 1446 | | zipAlign | ZipAlign | The task that zipaligns the apk. Can be null if the variant is a library or if the APK cannot be signed. | 1447 | | install | DefaultTask | The installation task. Can be null. | 1448 | | uninstall | DefaultTask | The uninstallation task. | 1449 | | connectedAndroidTest | DefaultTask | The task that runs the android tests on connected devices. | 1450 | | providerAndroidTest | DefaultTask | The task that runs the android tests using the extension API. | 1451 | 1452 | API for Android specific task types. 1453 | 1454 | * ProcessManifest 1455 | * File manifestOutputFile 1456 | * AidlCompile 1457 | * File sourceOutputDir 1458 | * RenderscriptCompile 1459 | * File sourceOutputDir 1460 | * File resOutputDir 1461 | * MergeResources 1462 | * File outputDir 1463 | * MergeAssets 1464 | * File outputDir 1465 | * ProcessAndroidResources 1466 | * File manifestFile 1467 | * File resDir 1468 | * File assetsDir 1469 | * File sourceOutputDir 1470 | * File textSymbolOutputDir 1471 | * File packageOutputFile 1472 | * File proguardOutputFile 1473 | * GenerateBuildConfig 1474 | * File sourceOutputDir 1475 | * Dex 1476 | * File outputFolder 1477 | * PackageApplication 1478 | * File resourceFile 1479 | * File dexFile 1480 | * File javaResourceDir 1481 | * File jniDir 1482 | * File outputFile 1483 | * To change the final output file use "outputFile" on the variant object directly. 1484 | * ZipAlign 1485 | * File inputFile 1486 | * File outputFile 1487 | * To change the final output file use "outputFile" on the variant object directly. 1488 | 1489 | The API for each task type is limited due to both how Gradle works and how the Android plugin sets them up. 1490 | 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. 1491 | 1492 | 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. 1493 | 1494 | 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. 1495 | 1496 | 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. 1497 | 1498 | For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation. 1499 | 1500 | ### 构建类型和Product Flavor属性引用 1501 | 1502 | coming soon. 1503 | For Gradle tasks (DefaultTask, JavaCompile, Copy, Zip), refer to the Gradle documentation. 1504 | 1505 | ### 使用sourceCompatibility 1.7 1506 | 1507 | 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: 1508 | 1509 | android { 1510 | compileSdkVersion 19 1511 | buildToolsVersion "19.0.0" 1512 | 1513 | defaultConfig { 1514 | minSdkVersion 7 1515 | targetSdkVersion 19 1516 | } 1517 | 1518 | compileOptions { 1519 | sourceCompatibility JavaVersion.VERSION_1_7 1520 | targetCompatibility JavaVersion.VERSION_1_7 1521 | } 1522 | } 1523 | 1524 | Note that you can use `minSdkVersion` with 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 `minSdkVersion` of 19. 1525 | 1526 | 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.) 1527 | 1528 | --- 1529 | 1530 | 原文地址:[http://tools.android.com/tech-docs/new-build-system/user-guide](http://tools.android.com/tech-docs/new-build-system/user-guide) 1531 | --------------------------------------------------------------------------------