Gradle Basics
自Android Studio发布以来,我逐步的将工作空间从Eclipse迁移过来,对于老伙伴Eclipse也越来越嫌弃。也难怪,Eclipse运行效率和体验一直为广大码农所诟病,连基本的列表滚动都不够平滑,而Android Studio在各方面都达到了优秀,极具科技感的ui也牢牢地抓住了广大Android码农的心。

重点在于Android Studio默认采用Gradle编译项目,而不是我们所熟知的Ant,在Gradle User Guide中能够看到Google给出的理由:
Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.
Here are some of its features that made us choose Gradle:
- Domain Specific Language (DSL) to describe and manipulate the build logic.
- Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
- Built-in dependency management through Maven and/or Ivy.
- Very flexible. Allows using best practices but doesn’t force its own way of doing things.
- Plugins can expose their own DSL and their own API for build files to use.
- Good Tooling API allowing IDE integration
Gradle是基于Groovy语言的,Groovy是一种运行于JVM的动态语言,语法与Java类似,并且可以在Groovy项目中引入Java代码块。这使得我大Java程序员可以低成本的定制编译逻辑。
Gradle文件结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | |
以上是一个基本的build.gradle文件,整体结构分为三个主要的部分:
1. buildscript { … } 这一块指定了编译环境,比如所依赖的gradle版本
2. apply plugin: ‘android-library’ 指定使用的插件,此文件指定的插件为’android-library’表明该项目是一个Lib项目,普通项目需指定为apply plugin: ‘android’
3. android { … } 项目参数,包含编译的SDK版本号,源码位置等。
依赖
常见的依赖有以下三种形式:
1 2 3 | |
多项目
Gradle对于Android Lib Project也提供了良好的支持,假设有一个项目其结构如下:
1 2 3 4 5 | |
我们可以指定三个项目,Gradle将以如下方式命名这几个项目:
1 2 3 | |
每个项目会包含一个build.gradle文件声明该项目的编译过程,而在根目录需要额外添加一个settings.gradle文件,用于声明项目。
1 2 3 4 5 6 7 8 9 | |
settings.gradle的内容非常简单:
1
| |
随后我们需要在:app这个项目中指名所依赖的项目:
1 2 3 4 | |
签名&混淆
直接看代码吧
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
ProductFlavors
这个功能可以用来打渠道包,以下配置可以在一次编译过程中生成beta 和 offical两种包,使用不同的manifest编译并且具备不同的versionName。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
命令行编译
由于之前使用Eclipse Export 的包十之八九不能用,给我留下了心理阴影,所以我个人比较倾向于使用命令行编译,并且这种编译方式能更清晰的看到编译过程。以往若是要在命令行中使用Ant必须先 update一下项目,而Android Studio创建的项目同时会创建build.gradle,所以只要配置好环境变量,在项目根目录执行如下命令即可。
1
| |