Android Gradle

  Gradle 是以 Groovy 语言为基础,面向Java应用为主。基于DSL(领域特定语言)语法的自动化构建工具。使用Gradle构建打包Android应用已经是当下主流处理方式了。这里记录一下个人在Android开发过程中,项目工程中用到的一些Gradle配置。

build.gradle

  • Project(项目) build.gradle文件:配置全局(整个工程)的gradle设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//工程中gradle 全局配置
ext {
android = [
applicationId : "me.onez.androidgradle",
compileSdkVersion: 23,
buildToolsVersion: "23.0.2",
minSdkVersion : 14,
targetSdkVersion : 22,
versionCode : 1,
versionName : "v1.0"
]

dependencies = [
"support-v4" : "com.android.support:support-v4:23.1.1",
"appcompat-v7" : "com.android.support:appcompat-v7:23.1.1",
"support-design" : "com.android.support:design:23.1.1",
"recyclerview-v7": "com.android.support:recyclerview-v7:23.1.1"
]
}
  • Module(模块)build.gradle文件:配置该模块的gradle设置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
android {
...
compileSdkVersion rootProject.ext.android.compileSdkVersion
buildToolsVersion rootProject.ext.android.buildToolsVersion


defaultConfig {
applicationId "me.onez.androidgradle"
minSdkVersion rootProject.ext.android.minSdkVersion
targetSdkVersion rootProject.ext.android.targetSdkVersion
versionCode rootProject.ext.android.versionCode
versionName rootProject.ext.android.versionName
}
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile rootProject.ext.dependencies["support-design"]
compile rootProject.ext.dependencies["appcompat-v7"]
compile rootProject.ext.dependencies["recyclerview-v7"]
compile rootProject.ext.dependencies["support-v4"]
}
}

gradle.properties

  • 可以配置gradle的一些属性引用,譬如签名相关的信息,如果有些信息不想提交到版本库,也可以配置到local.properties文件中
1
2
3
4
KEYSTORE_PASSWORD=xxx
KEY_PASSWORD=xxx
KEYSTORE_FILE=./xxx.keystore
KEY_ALIAS=xxx_key

然后在gradle中引用

1
2
3
4
5
6
7
8
signingConfigs {
release {
storeFile file(KEYSTORE_FILE)
storePassword KEYSTORE_PASSWORD
keyAlias KEY_ALIAS
keyPassword KEY_PASSWORD
}
}

product flavor

  • 打渠道包。

首先修改AndroidManifest.xml文件:

1
2
3
<meta-data
android:name="CHANNEL_NAME"
android:value="${CHANNEL_VALUE}" />

接着配置Module build.gradle文件:

1
2
3
4
5
6
7
8
9
10
11
12
//用于多渠道打包 flavor名如果是数字开头,必须用引号引起来
productFlavors {
wandoujia {
manifestPlaceholders = [CHANNEL_VALUE: "wandoujia"]
}
xiaomi {
manifestPlaceholders = [CHANNEL_VALUE: "xiaomi"]
}
"360" {
manifestPlaceholders = [CHANNEL_VALUE: "360"]
}
}

manifestPlaceholders 可以用来替换AndroidManifest中的占位符(${xxx})

Android Gralde Demo

AndroidGradle On My Github

资料参考

Gradle插件用户指南(译)/)

Android打包的那些事