When Google introduced Gradle and Android Studio, they had some goals in mind. They wanted to make it easier to reuse code, create build variants, and configure and customize the build process. On top of that, they wanted good IDE integration, but without making the build system dependent on the IDE. Running Gradle from the command line or on a continuous integration server will always yield the same results as running a build from Android Studio. html
We will refer to Android Studio occasionally throughout the book, because it often provides a simpler way of setting up projects, dealing with changes, and so on. If you do not have Android Studio installed yet, you can download it from the Android developer website ( http://developer.android.com/sdk/index.html ).
java
In this chapter, we will cover the following topics:
android
當Google推出Gradle和Android Studio時,他們有一些目標。他們但願可以更輕鬆地重用代碼,建立構建變量,以及配置和定製構建過程。最重要的是,他們但願有良好的IDE集成,可是不要使構建系統依賴於IDE。經過命令行或持續集成服務器運行Gradle將始終產生與經過Android Studio運行構建相同的結果。web
咱們將在本書中偶爾說起Android Studio,由於它常常提供一個更簡單的方法來設置項目,處理更改等等。 若是您尚未安裝Android Studio,能夠從Android開發者網站下載。shell
在本章中,咱們將介紹如下主題:
segmentfault
在gradle中有兩大重要的概念,分別是project和tasks。windows
每個構建都由至少一個project組成,每一個project都至少包含一個tasks。api
每個build.gradle文件表明着一個project,tasks在build.gradle中定義。bash
當初始化構建進程時,gradle會基於build文件,組合全部的project和tasks。服務器
一個tasks包含了一系列的動做,它們會按照順序執行。
一個動做就是一段被執行的代碼,它們很像Java中的方法。
一次構建將會經歷下列三個階段:
In the repositories block, the JCenter repository is configured as a source of dependencies for the build script. JCenter is a preconfigured Maven repository and requires no extra setup; Gradle has you covered. There are several repositories available straight from Gradle and it is easy to add your own, either local or remote.
The build script block also defines a dependency on Android build tools as a classpath Maven artifact. This is where the Android plugin comes from. The Android plugin provides everything needed to build and test applications. Every Android project needs to apply the Android plugin using this line:
apply plugin: 'com.android.application'
Plugins are used to extend the capabilities of a Gradle build script. Applying a plugin to a project makes it possible for the build script to define properties and use tasks that are defined in the plugin.
If you are building a library, you need to apply 'com.android. library' instead. You cannot use both in the same module because that would result in a build error. A module can be either an Android application or an Android library, not both.
When using the Android plugin, Android-specific conventions can be configured and tasks only applicable to Android will be generated. The Android block in the following snippet is defined by the plugin and can be configured per project:
android { compileSdkVersion 22 buildToolsVersion "22.0.1" }
This is where the Android-specific part of the build is configured. The Android plugin provides a DSL tailored to Android's needs. The only required properties are the compilation target and the build tools. The compilation target, specified by compileSdkVersion , is the SDK version that should be used to compile the app. It is good practice to use the latest Android API version as the compilation target.
There are plenty of customizable properties in the build.gradle file. We will discuss the most important properties in Chapter 2, Basic Build Customization, and more possibilities throughout the rest of the book.
buildscript { repositories { jcenter() //存儲庫 } dependencies { classpath 'com.android.tools.build:gradle:1.2.3' } }
buildscript {
repositories {
jcenter() //存儲庫
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
}
}
這就是對實際構建所作的配置。
在存儲庫塊中,JCenter存儲庫被配置爲構建腳本的依賴關係的來源。 JCenter是一個預先配置的Maven倉庫,不須要額外的設置,Gradle中有你的覆蓋。從Gradle中能夠直接找到幾個存儲庫,很容易添加你本身的或本地的或遠程的。
構建腳本塊還將Android構建工具的依賴性定義爲類路徑Maven構件。這就是Android plugin的來源之處。Android插件提供了構建和測試應用程序所需的一切。每一個Android項目都須要使用這一行來應用Android插件:
apply plugin: 'com.android.application'
apply plugin: 'com.android.application'
插件用於擴展Gradle構建腳本的功能。在一個項目中使用插件,這樣該項目的構建腳本就能夠定義該插件定義好的屬性和使用它的tasks。
注意:當你在開發一個依賴庫時,你應該使用:
apply plugin: 'com.android.library'
apply plugin: 'com.android.library'
你不能在同一個模塊中使用二者,這會致使構建錯誤。模塊能夠是Android應用程序或Android庫,而不能二者都是。
使用Android插件時,能夠配置特定於Android的約定,並僅生成適用於Android的task。如下代碼段中的Android代碼塊由插件定義,能夠爲每一個項目配置:
android { compileSdkVersion 22 buildToolsVersion "22.0.1" }
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
}
這是構建Android特定部分的地方。Android插件提供了一個適合Android需求的DSL。惟一須要的屬性是編譯目標和構建工具。由compileSdkVersion指定的編譯目標是用於編譯應用程序的SDK版本。使用最新的Android API版本做爲編譯目標是一個很好的作法。
build.gradle文件中有不少可定製的屬性。咱們將在第二章「基本構建定製」中討論最重要的屬性,以及經過本書其他部分討論更多可能性。
MyApp ├── build.gradle ├── settings.gradle └── app ├── build.gradle ├── build //The output of the build process ├── libs //These are external libraries (.jar or .aar) └── src └── main ├── java //The source code for the app │ └── com.package.myapp └── res //These are app-related resources (drawables, layouts, strings, and so on) ├── drawable ├── layout └── etc.
MyApp
├── build.gradle
├── settings.gradle
└── app
├── build.gradle
├── build //The output of the build process
├── libs //These are external libraries (.jar or .aar)
└── src
└── main
├── java //The source code for the app
│ └── com.package.myapp
└── res //These are app-related resources (drawables, layouts, strings, and so on)
├── drawable
├── layout
└── etc.
Gradle使用了一個叫作source set的概念,Gradle官方文檔解釋說:一個source set就是一系列資源文件,它們被一塊兒編譯和執行。對於Android項目,main就是一個包含了應用程序默認版本全部源代碼和資源的source set。當你開始爲你的Android應用程序編寫測試時,你將把測試的源代碼放在一個名爲androidTest的獨立源代碼集中,它只包含測試。
【Getting the Gradle Wrapper】
For your convenience, every new Android project includes the Gradle Wrapper, so when you create a new project, you do not have to do anything at all to get the necessary files. It is, of course, possible to install Gradle manually on your computer and use it for your project, but the Gradle Wrapper can do the same things and guarantee that the correct version of Gradle is used. There is no good reason not to use the wrapper when working with Gradle outside of Android Studio.
You can check if the Gradle Wrapper is present in your project by navigating to the project folder and running ./gradlew –v from the terminal or gradlew.bat –v from Command Prompt. Running this command displays the version of Gradle and some extra information about your setup. If you are converting an Eclipse project, the wrapper will not be present by default. In this case, it is possible to generate it using Gradle, but you will need to install Gradle first to get the wrapper.
After you have downloaded and installed Gradle and added it to your PATH , create a build.gradle file containing these three lines:
task wrapper(type: Wrapper) { gradleVersion = '2.4' }
After that, run gradle wrapper to generate the wrapper files.
In recent versions of Gradle, you can also run the wrapper task without modifying the build.gradle file, because it is included as a task by default. In that case, you can specify the version with the --gradle-version parameter, like this:
$ gradle wrapper --gradle-version 2.4
If you do not specify a version number, the wrapper is configured to use the Gradle version that the task is executed with.
These are all the files generated by the wrapper task:...
The gradle-wrapper.properties file is the one that contains the configuration and determines what version of Gradle is used:...
You can change the distribution URL if you want to use a customized Gradle distribution internally. This also means that any app or library that you use could have a different URL for Gradle, so be sure to check whether you can trust the properties before you run the wrapper.
Android Studio is kind enough to display a notification when the Gradle version used in a project is not up to date and will suggest automatically updating it for you. Basically, Android Studio changes the configuration in the gradle-wrapper. properties file and triggers a build, so that the latest version gets downloaded.
PS:Android Studio uses the information in the properties to determine which version of Gradle to use, and it runs the wrapper from the Gradle Wrapper directory inside your project. However, it does not make use of the shell or bash scripts, so you should not customize those.
爲了方便起見,每一個新的Android項目都包含了Gradle Wrapper,因此當你建立一個新的項目時,你不須要作任何事情來獲取必要的文件。固然,能夠在您的計算機上手動安裝Gradle,並將其用於您的項目,但Gradle Wrapper能夠作一樣的事情,並保證使用正確版本的Gradle。在Android Studio以外使用Gradle時,沒有理由不使用Gradle Wrapper。
您能夠經過導航到項目文件夾並從終端或命令行運行【gradlew -v】或【gradlew.bat -v】來檢查項目中是否存在Gradle Wrapper。運行此命令將顯示Gradle的版本以及有關您設置的一些額外信息。
若是你正在轉換一個Eclipse項目,默認狀況下,wrapper將不會出現。 在這種狀況下,可使用Gradle生成它,可是您須要首先安裝Gradle來獲取wrapper。
在您下載並安裝Gradle並將其添加到PATH後,建立一個包含如下三行的 build.gradle 文件(白注:在根目錄下的 build.gradle 文件中添加如下代碼便可):
task wrapper(type: Wrapper) { gradleVersion = '2.4' }
x
task wrapper(type: Wrapper) {
gradleVersion = '2.4'
}
以後,運行Gradle Wrapper來生成Wrapper文件(白注:添加上述代碼後同步一下便可生成完整的 gradle 目錄)。
在最近的Gradle版本中,你也能夠在不修改 build.gradle 文件的狀況下運行 wrapper task,由於默認狀況下它被包含爲一個task。在這種狀況下,您可使用【--gradle-version】參數指定版本,以下所示:
gradle wrapper --gradle-version 2.4
gradle wrapper --gradle-version 2.4
若是不指定版本號,則將wrapper配置爲使用執行task的Gradle版本。
下列是由wrapper task生成的全部文件:
myapp/ ├── gradlew //針對Linux和Mac系統的shell腳本文件, A shell script on Linux and Mac OS X ├── gradlew.bat //針對windows系統的bat文件,A batch file on Microsoft Windows └── gradle/wrapper/ ├── gradle-wrapper.jar //A JAR file that is used by the batch file and shell script └── gradle-wrapper.properties //配置文件,A properties file,用於肯定使用哪一個版本的Gradle
x
myapp/
├── gradlew //針對Linux和Mac系統的shell腳本文件, A shell script on Linux and Mac OS X
├── gradlew.bat //針對windows系統的bat文件,A batch file on Microsoft Windows
└── gradle/wrapper/
├── gradle-wrapper.jar //A JAR file that is used by the batch file and shell script
└── gradle-wrapper.properties //配置文件,A properties file,用於肯定使用哪一個版本的Gradle
【gradle-wrapper.properties】文件是一個包含配置並肯定使用哪一個版本的Gradle的文件:
#Sat May 30 17:41:49 CEST 2015 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
#Sat May 30 17:41:49 CEST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
若是您想在內部使用定製的Gradle,則能夠更改URL(可使用本地路徑)。這也意味着您使用的任何應用程序或庫均可能具備不一樣的Gradle URL,所以請務必在運行wrapper以前檢查是否能夠信任這些屬性。
若是項目中使用的Gradle版本不是最新的,Android Studio會提供足夠的通知,而且會建議您自動更新。基本上,Android Studio更改gradle-wrapper.properties中的配置並觸發構建,以便下載最新版本。
注意:Android Studio使用properties中的信息來肯定使用哪一個版本的Gradle,並運行你工程中Gradle Wrapper目錄的wrapper。可是,它並無使用shell或bash腳本,因此你不該該自定義這些。
gradlew tasks
gradlew tasks
這將打印出全部可用task列表(白注:第一次使用此命令會下載一些東西,大概要六到八分鐘)。若是添加--all參數,則能夠得到有關每一個task的依賴性的更詳細概述。
白注:這些列表和AS中Gradle面板中的一致。
> Task :tasks ------------------------------------------------------------ All tasks runnable from root project ------------------------------------------------------------ Android tasks ------------- androidDependencies - Displays the Android dependencies of the project. signingReport - Displays the signing info for each variant. sourceSets - Prints out all the source sets defined in this project. Build tasks ----------- assemble - Assembles all variants of all applications and secondary packages. assembleAndroidTest - Assembles all the Test applications. assembleDebug - Assembles all Debug builds. assembleRelease - Assembles all Release builds. build - Assembles and tests this project. buildDependents - Assembles and tests this project and all projects that depend on it. buildNeeded - Assembles and tests this project and all projects it depends on. clean - Deletes the build directory. cleanBuildCache - Deletes the build cache directory. compileDebugAndroidTestSources compileDebugSources compileDebugUnitTestSources compileReleaseSources compileReleaseUnitTestSources mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests. Build Setup tasks ----------------- init - Initializes a new Gradle build. Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'project'. components - Displays the components produced by root project 'project'. [incubating] dependencies - Displays all dependencies declared in root project 'project'. dependencyInsight - Displays the insight into a specific dependency in root project 'project'. dependentComponents - Displays the dependent components of components in root project 'project'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'project'. [incubating] projects - Displays the sub-projects of root project 'project'. properties - Displays the properties of root project 'project'. tasks - Displays the tasks runnable from root project 'project' (some of the displayed tasks may belong to subprojects). Install tasks ------------- installDebug - Installs the Debug build. installDebugAndroidTest - Installs the android (on device) tests for the Debug build. uninstallAll - Uninstall all applications. uninstallDebug - Uninstalls the Debug build. uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build. uninstallRelease - Uninstalls the Release build. Verification tasks ------------------ check - Runs all checks. connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices. connectedCheck - Runs all device checks on currently connected devices. connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices. deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers. deviceCheck - Runs all device checks using Device Providers and Test Servers. lint - Runs lint on all variants. lintDebug - Runs lint on the Debug build. lintRelease - Runs lint on the Release build. lintVitalRelease - Runs lint on just the fatal issues in the release build. test - Run unit tests for all variants. testDebugUnitTest - Run unit tests for the debug build. testReleaseUnitTest - Run unit tests for the release build. To see all tasks and more detail, run gradlew tasks --all To see more detail about a task, run gradlew help --task <task>
x
> Task :tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for each variant.
sourceSets - Prints out all the source sets defined in this project.
Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
cleanBuildCache - Deletes the build cache directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
mockableAndroidJar - Creates a version of android.jar that's suitable for unit tests.
Build Setup tasks
-----------------
init - Initializes a new Gradle build.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'project'.
components - Displays the components produced by root project 'project'. [incubating]
dependencies - Displays all dependencies declared in root project 'project'.
dependencyInsight - Displays the insight into a specific dependency in root project 'project'.
dependentComponents - Displays the dependent components of components in root project 'project'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'project'. [incubating]
projects - Displays the sub-projects of root project 'project'.
properties - Displays the properties of root project 'project'.
tasks - Displays the tasks runnable from root project 'project' (some of the displayed tasks may belong to subprojects).
Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug build.
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Debug build.
uninstallRelease - Uninstalls the Release build.
Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors on connected devices.
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected devices.
deviceAndroidTest - Installs and runs instrumentation tests using all Device Providers.
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
lintVitalRelease - Runs lint on just the fatal issues in the release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task <task>
注意:在Microsoft Windows上,您須要運行gradlew.bat,在Linux和Mac OS X上,完整的命令是./gradlew。爲了簡潔起見,咱們在整本書中只是寫做gradlew 。
要在開發過程當中構建項目,請使用調試配置運行組合的task(白注:第一次使用此命令也會下載一些東西):
gradlew assembleDebug
gradlew assembleDebug
此task將使用該應用程序的調試版本建立一個APK(白注:這和在Gradle面板中雙擊 build/assembleDebug 的效果一致)。默認狀況下,Gradle的Android插件將APK保存在 MyApp/app/build/outputs/apk 目錄中。
注意:使用縮寫的task名稱是爲了不在終端中輸入大量的內容,Gradle還提供駱駝風格縮寫的task名稱做爲快捷鍵。例如,能夠經過從命令行界面運行gradlew assDeb來執行assembleDebug,甚至能夠是aD。但這裏有一個警告,僅僅當駱駝風格的縮寫是惟一的狀況下它纔會起做用。一旦另外一個任務具備相同的縮寫,這個技巧就再也不適用於這些task。
除了assemble外,還有另外三個基本的任務:
咱們將在第2章基本構建定製中詳細討論這些任務。
1.1 Android Studio 1.1.1 保持最新 Staying up to date 1.3 建立新項目 Creating a new project 1.5 遷移出Eclipse Migrating from Eclipse 1.5.1 使用導入嚮導 Using the import wizard 1.5.2 手動遷移 Migrating manually 保持舊的項目結構 Keeping the old project structure 轉換到新的項目結構 Converting to the new project structure 遷移庫 Migrating libraries
1.1 Android Studio
1.1.1 保持最新 Staying up to date
1.3 建立新項目 Creating a new project
1.5 遷移出Eclipse Migrating from Eclipse
1.5.1 使用導入嚮導 Using the import wizard
1.5.2 手動遷移 Migrating manually
保持舊的項目結構 Keeping the old project structure
轉換到新的項目結構 Converting to the new project structure
遷移庫 Migrating libraries