一、全局设置
如果有很多项目,可以设置全局来统一管理版本号或依赖库,【项目的根目录】下build.gradle下:
- ext {
- compileSdkVersion = 23
- buildToolsVersion = "23.0.2"
- minSdkVersion = 14
- targetSdkVersion = 23
- }
app/build.gradle
- android {
- compileSdkVersion rootProject.ext.compileSdkVersion
- buildToolsVersion rootProject.ext.buildToolsVersion
-
- defaultConfig {
- applicationId "com.example.android"
- minSdkVersion rootProject.ext.minSdkVersion
- targetSdkVersion rootProject.ext.targetSdkVersion
- versionCode 1
- versionName "1.0"
- }
-
- }
二、添加新的module或者library
在setting.gradle中include
- include ':app', ':myfirstlib' #如果是一行,使用逗号分割
- include ':mysecondlib'
三、默认buildType扩展
android项目中,默认提供了三种类型,all、debug和release
- buildTypes {
- all{
- buildConfigField "String", "AppType", "\"Test\"" //自定义字段,在BuildConfig中生成
- }
- debug{
- buildConfigField "boolean", "IS_DEBUG", "true"
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
- release {
- buildConfigField "boolean", "IS_DEBUG", "false"
- minifyEnabled true
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
- }
如果想扩展buildType,需要使用initWith(默认的类型),注意,一般情况下initWith的参数不推荐all
- buildTypes {
- all{
- buildConfigField "String", "AppType", "\"Test\""
- }
- debug{
- buildConfigField "boolean", "IS_DEBUG", "true"
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
- release {
- buildConfigField "boolean", "IS_DEBUG", "false"
- minifyEnabled true
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
-
- myprojectDebug.initWith(debug)
- myprojectDebug{
- buildConfigField "String", "name", "myproject"
- }
- myprojectRelease.initWith(release)
- myprojectRelease{
- buildConfigField "String", "name", "myproject"
- }
- }
注意:主项目扩展buildType类型,意味着库项目也需要配置,对于存在多个库项目的情况下,我们推荐使用productFlavors来处理,可以达到同样的效果。
注意:buildType配置的渠道权重高于productFlavors,一切在productFlavors中配置的项都能被buildType中的配置项覆盖,比如buildConfigField,只要在all\debug\release中出现,那么productFlavors重的buildConfigField会被覆盖
四、manifestPlaceholders动态修改和覆盖
manifestPlaceholders += [key:value,...]
- buildTypes {
- all{
- buildConfigField "String", "AppType", "\"Test\""
- manifestPlaceholders = [
- "APP_NAME":"\"测试\"",
- "APP_VERSION":"210"
-
- ]
- }
- debug{
- manifestPlaceholders += ["APP_NAME":"\"测试1\""];
- buildConfigField "boolean", "IS_DEBUG", "true"
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
- release {
- manifestPlaceholders += ["APP_NAME":"\"正式版\""];
- buildConfigField "boolean", "IS_DEBUG", "false"
- minifyEnabled true
- proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
- }
-
-
- }
五、自定义字段
buildConfigField FIELD_TYPE,FIELD_NAME, VALUE
buildConfigField "String", "AppType", "\"Test\"" //自定义字段,在BuildConfig中生成
六、渠道定义
渠道定义存在维度,一个项目可以有多个维度,每个维度可以存在多个渠道
- flavorDimensions "channel" //维度
-
- productFlavors {
-
- xiaomi {
- dimension "channel" //告诉gradle,该渠道所属的维度
- buildConfigField "String", "channel", "\"xiaomi\""
- manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"]
- }
- qihoo360 {
- dimension "channel"
- buildConfigField "String", "channel", "\"qihoo360\""
- manifestPlaceholders = [UMENG_CHANNEL_VALUE: "qihoo360"]
- }
- baidu {
- dimension "channel"
- buildConfigField "String", "channel", "\"baidu\""
- manifestPlaceholders = [UMENG_CHANNEL_VALUE: "baidu"]
- }
-
- }
七、apk签名定义和使用
- android {
- signingConfigs {
- config {
- keyAlias 'yiba'
- keyPassword '123456'
- storeFile file('C:/work/Key.jks')
- storePassword '1234567'
- }
- }
-
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- signingConfig signingConfigs.config
- }
- debug {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- signingConfig signingConfigs.config
- }
- }
- }
签名的定义还可以根据buildType和flavor自行分类,具体参考gradle官网。
八、通过gradle.properties实现常量定义
我们通过ext可以定义常量,此外gradle.properties也是一种可行的办法
- # Project-wide Gradle settings.
- #添加ndk支持(按需添加)
- android.useDeprecatedNdk=true
- # 应用版本名称
- VERSION_NAME=1.0.0
- # 应用版本号
- VERSION_CODE=100
- # 支持库版本
- SUPPORT_LIBRARY=24.2.1
- # MIN_SDK_VERSION
- ANDROID_BUILD_MIN_SDK_VERSION=14
- # TARGET_SDK_VERSION
- ANDROID_BUILD_TARGET_SDK_VERSION=24
- # BUILD_SDK_VERSION
- ANDROID_BUILD_SDK_VERSION=24
- # BUILD_TOOLS_VERSION
- ANDROID_BUILD_TOOLS_VERSION=24.0.3
这时候配置app和lib的build.gradle可以这样写:
- android {
- compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
- buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
-
- defaultConfig {
- applicationId project.APPLICATION_ID // lib项目不需要配置这一项
- versionCode project.VERSION_CODE as int
- versionName project.VERSION_NAME
- minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
- targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
- }
- }
-
- dependencies {
- compile fileTree(include: ['*.jar'], dir: 'libs')
- //这里注意是双引号
- compile "com.android.support:appcompat-v7:${SUPPORT_LIBRARY}"
- compile "com.android.support:design:${SUPPORT_LIBRARY}"
- compile "com.android.support:recyclerview-v7:${SUPPORT_LIBRARY}"
- compile "com.android.support:support-annotations:${SUPPORT_LIBRARY}"
- compile "com.android.support:cardview-v7:${SUPPORT_LIBRARY}"
- compile "com.android.support:support-v4:${SUPPORT_LIBRARY}"
- }
九、忽略lint检测导致编译终止
- android {
-
- lintOptions {
- abortOnError false
- }
-
- }
十、resConfigs过滤语言
- android {
-
- defaultConfig {
- applicationId "com.yiba.sharewe.lite.activity"
- minSdkVersion 14
- targetSdkVersion 24
- versionCode 46
- versionName "1.74"
- resConfigs 'en', 'zh-rCN' ,'es' //本次打包,只把 en(英文)、zh-rCN(中文简体)、es(西班牙语)打进保内,其他语言忽略
- }
- }
十一、差异化依赖
- dependencies {
-
- //打 debug 包
- debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
-
- //打 release 包
- releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
-
- }
十二、定义多个源码目录
- android {
-
- sourceSets {
- main {
- java {
- srcDir 'src/test1' //指定 test1 为源码目录
- srcDir 'src/test2' //指定 test2 为源码目录
- srcDir 'src/test3' //指定 test3 为源码目录
- }
- }
- }
- }
十二、定义 APK 包的名字
- android {
-
- defaultConfig {
- applicationId "android.plugin"
- minSdkVersion 14
- targetSdkVersion 25
- versionCode 1
- versionName "1.0"
- }
-
- buildTypes {
- release {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- debug {
- minifyEnabled false
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
- }
- }
-
- //定义渠道
- productFlavors {
- xiaomi {
- //小米
- }
- wandoujia {
- // 豌豆荚
- }
- }
-
- //打包命名
- applicationVariants.all {
- variant ->
- variant.outputs.each {
- output ->
-
- //定义一个新的apk 名字。
- // 新名字 = app 名字+ 渠道号 + 构建类型 + 版本号 + 当前构建时间
- def apkName = "appName_${variant.flavorName}_${buildType.name}_v${variant.versionName}_${getTime()}.apk";
- output.outputFile = new File(output.outputFile.parent, apkName);
- }
- }
-
- }
-
- //获取当前时间
- def getTime() {
- String today = new Date().format('YY年MM月dd日HH时mm分') //gradle支持java语法
- return today
- }
十三、buildTypes常用属性
- name:build type的名字
-
- applicationIdSuffix:应用id后缀
-
- versionNameSuffix:版本名称后缀
-
- debuggable:是否生成一个debug的apk
-
- minifyEnabled:是否混淆
-
- proguardFiles:混淆文件
-
- signingConfig:签名配置
-
- manifestPlaceholders:清单占位符
-
- shrinkResources:是否去除未利用的资源,默认false,表示不去除。
-
- zipAlignEnable:是否使用zipalign工具压缩。
-
- multiDexEnabled:是否拆成多个Dex
-
- multiDexKeepFile:指定文本文件编译进主Dex文件中
-
- multiDexKeepProguard:指定混淆文件编译进主Dex文件中
十四、jni和aidl支持
- android {
-
- sourceSets {
- main {
- jniLibs.srcDirs //定义 jni 目录
- aidl.srcDirs //定义 aidl 目录
- }
- }
- }
十五、定义变量
- def map=['key1':1,'key2':2]
- def isDEBUG = true
十六、依赖排除
- //排除哪个jar的依赖
- compile('org.spring-core:3.6.3.Final'){
- //指定要排除的依赖的group和module=name,不指定版本,默认排除最低版本
- exclude group:'org.slf4j',module:'slf4j-api'
- //transitive=false//排除所有传递性依赖,比较少用
- }
十七、策略
gradle提供了configurations,可以对各种渠道(包括自定义渠道)和各种类型(包括最定义buildType)设置策略
- configurations.all{
- resolutionStrategy{
- failOnVersionConflict()
- }
- }
-
- //all表示所有构建类型,当然,如果你自定义了如baiduDebug,那么你可以单独为此类型做策略设置
- configurations.baiduDebug{
- resolutionStrategy{
- failOnVersionConflict()
- }
- }
十八、构建过程生命周期监听
-
-
- //自定义的log输出
- class CustomEventLogger implements BuildListener, TaskExecutionListener {
- @Override
- void buildStarted(Gradle gradle) {
- println "buildStarted"
- }
-
- @Override
- void settingsEvaluated(Settings settings) {
- println "settingsEvaluated"
- }
-
- @Override
- void projectsLoaded(Gradle gradle) {
- println "projectsLoaded"
- }
-
- @Override
- void projectsEvaluated(Gradle gradle) {
- println "projectsEvaluated"
- }
-
- public void beforeExecute(Task task) {
- println "beforeExecute:[$task.name]"
- }
-
- public void afterExecute(Task task, TaskState state) {
- println "afterExecute:[$task.name]"
- }
-
- public void buildFinished(BuildResult result) {
- println 'buildFinished'
- if (result.failure != null) {
- result.failure.printStackTrace()
- }
- }
- }
使用方法
- 方法1
- gradle.useLogger(new CustomEventLogger())
- 方法2
- gradle.addBuildListener(new CustomEventLogger())
此外,还有一种监听配置方式
- /**
- * 同上BuildListener和ProjectEvaluationListener
- */
- gradle.buildStarted {
- gradle.println "=========buildStarted========="
- }
- gradle.settingsEvaluated {
- gradle.println "=========settingsEvaluated========="
- }
- gradle.projectsLoaded {
- gradle.println "=========projectsLoaded========="
- }
- gradle.projectsEvaluated {
- gradle.println "=========projectsEvaluated========="
- }
- gradle.buildFinished {
- gradle.println "=========buildFinished========="
- }
- gradle.beforeProject {
- gradle.println "=========beforeProject========="
- }
- gradle.afterProject {
- gradle.println "=========afterProject========="
- }
参考:https://www.cnblogs.com/duex/p/9205155.html
十九、task及task生命周期
task定义
- //定义任务1
- task task1{
- println 'task1'
- }
-
- //定义任务2
- task task2{
- println 'task2'
- }
-
- //通过create创建任务3
- tasks.create(name: 'hello4') {
- println 'hello4'
- }
-
- //通过注解和参数注入实现复杂功能,任务4
-
- //局部自定义Task
- //直接在build.gradle中自定义Task
- //但是也只能在当前module中引用
- class TestCustomTask extends DefaultTask {
- //@Optional,表示在配置该Task时,message是可选的。
- @Optional
- String message = 'I am jjx'
- //@TaskAction表示该Task要执行的动作,即在调用该Task时,hello()方法将被执行
- @TaskAction
- def hello() {
- println "hello world $message"
- }
- }
-
- //hello使用了默认的message值
- task hello(type: TestCustomTask)
-
- //重新设置了message的值
- task helloOne(type: TestCustomTask) {
- message = "I am a android developer"
- }
task依赖
- 方法1
- task2.dependsOn task1
- 方法2
- task hello5(dependsOn:hello4) {
- println 'hello5'
- }
task生命周期
- task testTask {
-
- println 'testTask << print'
-
- // 表示在task最前面来执行的过程
- doFirst {
- println 'testTask do first'
- }
- // << 和 doLast表示对当前task追加执行过程,效果是一样的
- doLast{
- println 'testTask do last!'
- }
-
- afterEvaluate { //在配置读取阶段执行,总在doFirst之前
- println '---->afterEvaluate'
- }
- }
参考:https://www.jianshu.com/p/ed4ef3b96a29