当前位置:   article > 正文

gradle 常用知识点总结

gradle知识

一、全局设置

如果有很多项目,可以设置全局来统一管理版本号或依赖库,【项目的根目录】下build.gradle下:

  1. ext {
  2. compileSdkVersion = 23
  3. buildToolsVersion = "23.0.2"
  4. minSdkVersion = 14
  5. targetSdkVersion = 23
  6. }

app/build.gradle

  1. android {
  2. compileSdkVersion rootProject.ext.compileSdkVersion
  3. buildToolsVersion rootProject.ext.buildToolsVersion
  4. defaultConfig {
  5. applicationId "com.example.android"
  6. minSdkVersion rootProject.ext.minSdkVersion
  7. targetSdkVersion rootProject.ext.targetSdkVersion
  8. versionCode 1
  9. versionName "1.0"
  10. }
  11. }

 

二、添加新的module或者library

在setting.gradle中include 

  1. include ':app', ':myfirstlib' #如果是一行,使用逗号分割
  2. include ':mysecondlib'

 

三、默认buildType扩展

android项目中,默认提供了三种类型,all、debug和release

  1. buildTypes {
  2. all{
  3. buildConfigField "String", "AppType", "\"Test\"" //自定义字段,在BuildConfig中生成
  4. }
  5. debug{
  6. buildConfigField "boolean", "IS_DEBUG", "true"
  7. minifyEnabled false
  8. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  9. }
  10. release {
  11. buildConfigField "boolean", "IS_DEBUG", "false"
  12. minifyEnabled true
  13. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  14. }
  15. }

如果想扩展buildType,需要使用initWith(默认的类型),注意,一般情况下initWith的参数不推荐all

  1. buildTypes {
  2. all{
  3. buildConfigField "String", "AppType", "\"Test\""
  4. }
  5. debug{
  6. buildConfigField "boolean", "IS_DEBUG", "true"
  7. minifyEnabled false
  8. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  9. }
  10. release {
  11. buildConfigField "boolean", "IS_DEBUG", "false"
  12. minifyEnabled true
  13. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  14. }
  15. myprojectDebug.initWith(debug)
  16. myprojectDebug{
  17. buildConfigField "String", "name", "myproject"
  18. }
  19. myprojectRelease.initWith(release)
  20. myprojectRelease{
  21. buildConfigField "String", "name", "myproject"
  22. }
  23. }

注意:主项目扩展buildType类型,意味着库项目也需要配置,对于存在多个库项目的情况下,我们推荐使用productFlavors来处理,可以达到同样的效果。

注意:buildType配置的渠道权重高于productFlavors,一切在productFlavors中配置的项都能被buildType中的配置项覆盖,比如buildConfigField,只要在all\debug\release中出现,那么productFlavors重的buildConfigField会被覆盖

四、manifestPlaceholders动态修改和覆盖

manifestPlaceholders +=  [key:value,...]

  1. buildTypes {
  2. all{
  3. buildConfigField "String", "AppType", "\"Test\""
  4. manifestPlaceholders = [
  5. "APP_NAME":"\"测试\"",
  6. "APP_VERSION":"210"
  7. ]
  8. }
  9. debug{
  10. manifestPlaceholders += ["APP_NAME":"\"测试1\""];
  11. buildConfigField "boolean", "IS_DEBUG", "true"
  12. minifyEnabled false
  13. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  14. }
  15. release {
  16. manifestPlaceholders += ["APP_NAME":"\"正式版\""];
  17. buildConfigField "boolean", "IS_DEBUG", "false"
  18. minifyEnabled true
  19. proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
  20. }
  21. }

 

五、自定义字段

buildConfigField FIELD_TYPE,FIELD_NAME, VALUE 

buildConfigField "String", "AppType", "\"Test\""  //自定义字段,在BuildConfig中生成

 

六、渠道定义

渠道定义存在维度,一个项目可以有多个维度,每个维度可以存在多个渠道

  1. flavorDimensions "channel" //维度
  2. productFlavors {
  3. xiaomi {
  4. dimension "channel" //告诉gradle,该渠道所属的维度
  5. buildConfigField "String", "channel", "\"xiaomi\""
  6. manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"]
  7. }
  8. qihoo360 {
  9. dimension "channel"
  10. buildConfigField "String", "channel", "\"qihoo360\""
  11. manifestPlaceholders = [UMENG_CHANNEL_VALUE: "qihoo360"]
  12. }
  13. baidu {
  14. dimension "channel"
  15. buildConfigField "String", "channel", "\"baidu\""
  16. manifestPlaceholders = [UMENG_CHANNEL_VALUE: "baidu"]
  17. }
  18. }

七、apk签名定义和使用

  1. android {
  2. signingConfigs {
  3. config {
  4. keyAlias 'yiba'
  5. keyPassword '123456'
  6. storeFile file('C:/work/Key.jks')
  7. storePassword '1234567'
  8. }
  9. }
  10. buildTypes {
  11. release {
  12. minifyEnabled false
  13. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  14. signingConfig signingConfigs.config
  15. }
  16. debug {
  17. minifyEnabled false
  18. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  19. signingConfig signingConfigs.config
  20. }
  21. }
  22. }

签名的定义还可以根据buildType和flavor自行分类,具体参考gradle官网。

八、通过gradle.properties实现常量定义

我们通过ext可以定义常量,此外gradle.properties也是一种可行的办法

  1. # Project-wide Gradle settings.
  2. #添加ndk支持(按需添加)
  3. android.useDeprecatedNdk=true
  4. # 应用版本名称
  5. VERSION_NAME=1.0.0
  6. # 应用版本号
  7. VERSION_CODE=100
  8. # 支持库版本
  9. SUPPORT_LIBRARY=24.2.1
  10. # MIN_SDK_VERSION
  11. ANDROID_BUILD_MIN_SDK_VERSION=14
  12. # TARGET_SDK_VERSION
  13. ANDROID_BUILD_TARGET_SDK_VERSION=24
  14. # BUILD_SDK_VERSION
  15. ANDROID_BUILD_SDK_VERSION=24
  16. # BUILD_TOOLS_VERSION
  17. ANDROID_BUILD_TOOLS_VERSION=24.0.3

这时候配置app和lib的build.gradle可以这样写:

  1. android {
  2. compileSdkVersion project.ANDROID_BUILD_SDK_VERSION as int
  3. buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
  4. defaultConfig {
  5. applicationId project.APPLICATION_ID // lib项目不需要配置这一项
  6. versionCode project.VERSION_CODE as int
  7. versionName project.VERSION_NAME
  8. minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION as int
  9. targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION as int
  10. }
  11. }
  12. dependencies {
  13. compile fileTree(include: ['*.jar'], dir: 'libs')
  14. //这里注意是双引号
  15. compile "com.android.support:appcompat-v7:${SUPPORT_LIBRARY}"
  16. compile "com.android.support:design:${SUPPORT_LIBRARY}"
  17. compile "com.android.support:recyclerview-v7:${SUPPORT_LIBRARY}"
  18. compile "com.android.support:support-annotations:${SUPPORT_LIBRARY}"
  19. compile "com.android.support:cardview-v7:${SUPPORT_LIBRARY}"
  20. compile "com.android.support:support-v4:${SUPPORT_LIBRARY}"
  21. }

九、忽略lint检测导致编译终止

  1. android {
  2. lintOptions {
  3. abortOnError false
  4. }
  5. }

十、resConfigs过滤语言

  1. android {
  2. defaultConfig {
  3. applicationId "com.yiba.sharewe.lite.activity"
  4. minSdkVersion 14
  5. targetSdkVersion 24
  6. versionCode 46
  7. versionName "1.74"
  8. resConfigs 'en', 'zh-rCN' ,'es' //本次打包,只把 en(英文)、zh-rCN(中文简体)、es(西班牙语)打进保内,其他语言忽略
  9. }
  10. }

十一、差异化依赖

  1. dependencies {
  2. //打 debug 包
  3. debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
  4. //release
  5. releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
  6. }

十二、定义多个源码目录

  1. android {
  2.     sourceSets {
  3.         main {
  4.             java {
  5.                 srcDir 'src/test1' //指定 test1 为源码目录
  6.                 srcDir 'src/test2' //指定 test2 为源码目录
  7.                 srcDir 'src/test3' //指定 test3 为源码目录
  8.             }
  9.         }
  10.     }
  11. }

 

十二、定义 APK 包的名字

  1. android {
  2. defaultConfig {
  3. applicationId "android.plugin"
  4. minSdkVersion 14
  5. targetSdkVersion 25
  6. versionCode 1
  7. versionName "1.0"
  8. }
  9. buildTypes {
  10. release {
  11. minifyEnabled false
  12. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  13. }
  14. debug {
  15. minifyEnabled false
  16. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  17. }
  18. }
  19. //定义渠道
  20. productFlavors {
  21. xiaomi {
  22. //小米
  23. }
  24. wandoujia {
  25. // 豌豆荚
  26. }
  27. }
  28. //打包命名
  29. applicationVariants.all {
  30. variant ->
  31. variant.outputs.each {
  32. output ->
  33. //定义一个新的apk 名字。
  34. // 新名字 = app 名字+ 渠道号 + 构建类型 + 版本号 + 当前构建时间
  35. def apkName = "appName_${variant.flavorName}_${buildType.name}_v${variant.versionName}_${getTime()}.apk";
  36. output.outputFile = new File(output.outputFile.parent, apkName);
  37. }
  38. }
  39. }
  40. //获取当前时间
  41. def getTime() {
  42. String today = new Date().format('YY年MM月dd日HH时mm分') //gradle支持java语法
  43. return today
  44. }

十三、buildTypes常用属性

  1. name:build type的名字
  2. applicationIdSuffix:应用id后缀
  3. versionNameSuffix:版本名称后缀
  4. debuggable:是否生成一个debug的apk
  5. minifyEnabled:是否混淆
  6. proguardFiles:混淆文件
  7. signingConfig:签名配置
  8. manifestPlaceholders:清单占位符
  9. shrinkResources:是否去除未利用的资源,默认false,表示不去除。
  10. zipAlignEnable:是否使用zipalign工具压缩。
  11. multiDexEnabled:是否拆成多个Dex
  12. multiDexKeepFile:指定文本文件编译进主Dex文件中
  13. multiDexKeepProguard:指定混淆文件编译进主Dex文件中

十四、jni和aidl支持

  1. android {
  2. sourceSets {
  3. main {
  4. jniLibs.srcDirs //定义 jni 目录
  5. aidl.srcDirs //定义 aidl 目录
  6. }
  7. }
  8. }

十五、定义变量

  1. def map=['key1':1,'key2':2]
  2. def isDEBUG = true

 

十六、依赖排除

  1. //排除哪个jar的依赖
  2. compile('org.spring-core:3.6.3.Final'){
  3. //指定要排除的依赖的group和module=name,不指定版本,默认排除最低版本
  4. exclude group:'org.slf4j',module:'slf4j-api'
  5. //transitive=false//排除所有传递性依赖,比较少用
  6. }

 

十七、策略

gradle提供了configurations,可以对各种渠道(包括自定义渠道)和各种类型(包括最定义buildType)设置策略

  1. configurations.all{
  2. resolutionStrategy{
  3. failOnVersionConflict()
  4. }
  5. }
  6. //all表示所有构建类型,当然,如果你自定义了如baiduDebug,那么你可以单独为此类型做策略设置
  7. configurations.baiduDebug{
  8. resolutionStrategy{
  9. failOnVersionConflict()
  10. }
  11. }

 

十八、构建过程生命周期监听

  1. //自定义的log输出
  2. class CustomEventLogger implements BuildListener, TaskExecutionListener {
  3. @Override
  4. void buildStarted(Gradle gradle) {
  5. println "buildStarted"
  6. }
  7. @Override
  8. void settingsEvaluated(Settings settings) {
  9. println "settingsEvaluated"
  10. }
  11. @Override
  12. void projectsLoaded(Gradle gradle) {
  13. println "projectsLoaded"
  14. }
  15. @Override
  16. void projectsEvaluated(Gradle gradle) {
  17. println "projectsEvaluated"
  18. }
  19. public void beforeExecute(Task task) {
  20. println "beforeExecute:[$task.name]"
  21. }
  22. public void afterExecute(Task task, TaskState state) {
  23. println "afterExecute:[$task.name]"
  24. }
  25. public void buildFinished(BuildResult result) {
  26. println 'buildFinished'
  27. if (result.failure != null) {
  28. result.failure.printStackTrace()
  29. }
  30. }
  31. }

使用方法

  1. 方法1
  2. gradle.useLogger(new CustomEventLogger())
  3. 方法2
  4. gradle.addBuildListener(new CustomEventLogger())

 

此外,还有一种监听配置方式

  1. /**
  2. * 同上BuildListener和ProjectEvaluationListener
  3. */
  4. gradle.buildStarted {
  5. gradle.println "=========buildStarted========="
  6. }
  7. gradle.settingsEvaluated {
  8. gradle.println "=========settingsEvaluated========="
  9. }
  10. gradle.projectsLoaded {
  11. gradle.println "=========projectsLoaded========="
  12. }
  13. gradle.projectsEvaluated {
  14. gradle.println "=========projectsEvaluated========="
  15. }
  16. gradle.buildFinished {
  17. gradle.println "=========buildFinished========="
  18. }
  19. gradle.beforeProject {
  20. gradle.println "=========beforeProject========="
  21. }
  22. gradle.afterProject {
  23. gradle.println "=========afterProject========="
  24. }

参考:https://www.cnblogs.com/duex/p/9205155.html

十九、task及task生命周期

task定义

  1. //定义任务1
  2. task task1{
  3. println 'task1'
  4. }
  5. //定义任务2
  6. task task2{
  7. println 'task2'
  8. }
  9. //通过create创建任务3
  10. tasks.create(name: 'hello4') {
  11. println 'hello4'
  12. }
  13. //通过注解和参数注入实现复杂功能,任务4
  14. //局部自定义Task
  15. //直接在build.gradle中自定义Task
  16. //但是也只能在当前module中引用
  17. class TestCustomTask extends DefaultTask {
  18. //@Optional,表示在配置该Task时,message是可选的。
  19. @Optional
  20. String message = 'I am jjx'
  21. //@TaskAction表示该Task要执行的动作,即在调用该Task时,hello()方法将被执行
  22. @TaskAction
  23. def hello() {
  24. println "hello world $message"
  25. }
  26. }
  27. //hello使用了默认的message值
  28. task hello(type: TestCustomTask)
  29. //重新设置了message的值
  30. task helloOne(type: TestCustomTask) {
  31. message = "I am a android developer"
  32. }

task依赖

  1. 方法1
  2. task2.dependsOn task1
  3. 方法2
  4. task hello5(dependsOn:hello4) {
  5. println 'hello5'
  6. }

task生命周期

  1. task testTask {
  2. println 'testTask << print'
  3. // 表示在task最前面来执行的过程
  4. doFirst {
  5. println 'testTask do first'
  6. }
  7. // << 和 doLast表示对当前task追加执行过程,效果是一样的
  8. doLast{
  9. println 'testTask do last!'
  10. }
  11. afterEvaluate { //在配置读取阶段执行,总在doFirst之前
  12. println '---->afterEvaluate'
  13. }
  14. }

参考:https://www.jianshu.com/p/ed4ef3b96a29

 

转载于:https://my.oschina.net/ososchina/blog/2993815

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/923275?site
推荐阅读
相关标签
  

闽ICP备14008679号