Gradle 学习积累

基础


Gradle Guides

命令

# 多任务顺序执行
gradlew clean jar

Groovy 基本

D:\workspace\project\gradle\basic-demo\build.gradle

Gradle Task 语法

D:\workspace\project\gradle\basic-demo\build.gradle

  1. task create
  2. task dependon
  3. myTask.doFirst

依赖管理

1. 查看当前依赖关系

gradlew :sample:dependencies

+--- project :jobslibs
|    +--- com.android.support:appcompat-v7:27.1.1
|    |    +--- com.android.support:support-annotations:27.1.1
|    |    +--- com.android.support:support-core-utils:27.1.1
|    |    |    +--- com.android.support:support-annotations:27.1.1
|    |    |    \--- com.android.support:support-compat:27.1.1
|    |    |         +--- com.android.support:support-annotations:27.1.1
|    |    |         \--- android.arch.lifecycle:runtime:1.1.0
|    |    |              +--- android.arch.lifecycle:common:1.1.0
|    |    |              \--- android.arch.core:common:1.1.0
|    |    +--- com.android.support:support-fragment:27.1.1
|    |    |    +--- com.android.support:support-compat:27.1.1 (*)

2. 排除传递依赖

参考:Gradle依赖项学习总结

指定某个模块

dependencies {
    compile ('org.codehaus.cargo:cargo-ant:1.3.1') {
        exclude group: 'xml-apis', module: 'xml-apis'
    }
    compile  'xml-apis:xml-apis:2.0.2'
}

中断引用库的依赖,不引用引用的引用

dependencies {
    compile ('org.codehaus.cargo:cargo-ant:1.3.1') {
        transitive=false
    }
}

版本冲突 Force强制使用某个模块

configurations.all {
   resolutionStrategy {
       force 'org.hamcrest:hamcrest-core:1.3'
   }
}
dependencies {
   androidTestCompile('com.android.support.test:runner:0.2')
   androidTestCompile('com.android.support.test:rules:0.2')
   androidTestCompile('com.android.support.test.espresso:espresso-core:2.1')
}
Android dependency 'androidx.exifinterface:exifinterface' has different version for the compile (1.0.0-rc01) and runtime (1.1.0-beta01) classpath. You should manually set the same version via DependencyResolution

解决

allprojects {
    repositories {
    }
    subprojects{
        project.configurations.all{
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'androidx.exifinterface'
                    && details.requested.name.contains('exifinterface')) {
                    details.useVersion "1.0.0-rc01"
                }
            }
        }
    }
}

配置相关

强制刷新依赖

gradlew --refresh-dependencies assemble

调试

查看属性(ext)

设置属性 gradle.properties

description = "A trivial Gradle build"
version = "1.0"

查看

./gradlew properties

任务调试

./gradlew task_cmd --scan

打印堆栈信息

# --stacktrace
./gradlew task_cmd -s
# --full-stacktrace
./gradlew task_cmd -S

自定义日志级别输出

# out quiet > level log 
gradle -q task_cmd
# out info > level log 
gradle -i task_cmd

使用gradle内置 logger 日志

task logTask {
  doLast {
    println 'Hello world!'
    logger.quiet('quiet log ...')
    logger.error('error log ...')
    logger.lifecycle('lifecycle log info ...')
    logger.info('info log...')
    logger.debug('debug ... ')
  }
}

获取Task命令的命令选项,例如:

gradlew help --task init

输出如下:

> Task :help 
Detailed task information for init

Path
     :init

Type
     InitBuild (org.gradle.buildinit.tasks.InitBuild)

Options
     --dsl     Set alternative build script DSL to be used.
               Available values are:
                    groovy
                    kotlin

     --test-framework     Set alternative test framework to be used.
                          Available values are:
                               spock
                               testng

     --type     Set type of build to create.
                Available values are:
                     basic
                     groovy-application
                     groovy-library
                     java-application
                     java-library
                     pom
                     scala-library

Description
     Initializes a new Gradle build.

Group
     Build Setup

附录

博客

资料

Google

*Android Studio Project Site *

插件

  • hugo JakeWharton 不必介绍了。项目中使用Gradle plugin 和自定义Task 顺便学习一些Process Annotation.
  • https://plugins.gradle.org/ plugins gradle plugin确定

开源插件


Android studio 使用

gradle.properties

  1. build.gradle使用gradle.properties

    gradle.properties

    VERSION_CODE=111
    VERSION_NAME=2.8.5
    STORE_PASSWORD=123456

    build.gradle 读取出来默认为String类型

    versionCode Integer.parseInt(VERSION_CODE)
    versionName VERSION_NAME
    //或
    versionCode Integer.parseInt(project.VERSION_CODE)
    versionName project.VERSION_NAME

使用案例

问题解决


依赖更新

项目依赖的远程包如果有更新,会有提醒或者自动更新吗? 不会的,需要你手动设置changing标记为true,这样gradle会每24小时检查更新,通过更改resolutionStrategy可以修改检查周期。

configurations.all {
// check for updates every build
resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}
dependencies {
compile group: "group", name: "projectA", version: "1.1-SNAPSHOT", changing: true
}

之前上传aar同一版本到maven仓库,但依赖却没有更新,该怎么办呢?可以直接删除本地缓存,缓存在~/.gradle/caches目录下,删除缓存后,下次运行就会自动重新下载远程依赖了。

Gradle下载慢5个解决方案

原因: 由于 services.gradle.org 国内下载速度很慢(一般为45kb/s), 而每个gradle-xx.xx.-all.zip 版本至少60MB, 也就正常是需要40分钟左右,花都谢了

#Mon Oct 22 23:20:47 CST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#把*4.6-all.zip 改为4.6-bin.zip 需要下载的更小
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
# 解决Gradle下载慢的问题
#方案一:使用本地缓存,修改.. distributions/gradle-4.6-all.zip 为本地已经有的版本

#方案二 1.把下载好的 gradle-x.x.x-all.zip 如:gradle-4.6-all.zip
# 1.1直接复制到 gradle-wrapper.properties 同在目录
# 1.2 如下:
#distributionUrl=gradle-4.6-all.zip

#方案三:引用本地文件地址
#1. Window
#distributionUrl=file:///E://software//2.coder//env//gradle-4.6-all.zip
#2. Unix
#distributionUrl=file\:/tmp/gradle-2.2.1-all.zip

#方案四:手动(国内或者浏览器)下载一般比较快,解压到gradle缓存目录
# 参考:https://www.cnblogs.com/rainboy2010/p/7062279.html
# 1. 缓存目录
# 1.1 window默认 : C:\Users\xxx(用户名)\.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9
# 1.2 unix默认: ~/.gradle/...
# 2. 获取base36值,参考FileTest#getDistMD5方法
#messageDigest = MessageDigest.getInstance("MD5");
#messageDigest.update(distributionUrl.getBytes());
#String str = new BigInteger(1, messageDigest.digest()).toString(36);
# 3. 在dist\gradle-3.3-all\ 下
# 3.1 新建文件,名为获取base36值
# 3.2 拷贝下载好的gradle-x.x.x-all.zip 到新建的文件,并解压

#方案五: 直接更改 distributionUrl的下载路径为国内服务器,例如:http://mirrors.flysnow.org/
#如:distributionUrl=http\://mirrors.flysnow.org/gradle/gradle-4.1-bin.zip
#注意 1. 镜像网站有指定版本;2. 不要设置代理
#如果你在 gradle.properties 配置了代理,请添加一个不走代理的配置,否则 gralde 无法安装
#systemProp.http.proxyHost=mirrors.neusoft.edu.cn
#systemProp.http.proxyPort=80
## 添加不走代理的 host,会影响 package 的安装
#systemProp.http.nonProxyHosts=172.1.1.227|localhost|mirrors.flysnow.org

依赖下载慢,使用阿里云国内镜像

单个项目生效

buildscript {
    repositories {
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
        maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
}
allprojects {
    repositories {
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
        maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}
    }
}

对所有项目生效,在USER_HOME/.gradle/下创建init.gradle文件

allprojects{
    repositories {
        def ALIYUN_REPOSITORY_URL = 'http://maven.aliyun.com/nexus/content/groups/public'
        def ALIYUN_JCENTER_URL = 'http://maven.aliyun.com/nexus/content/repositories/jcenter'
        all { ArtifactRepository repo ->
            if(repo instanceof MavenArtifactRepository){
                def url = repo.url.toString()
                if (url.startsWith('https://repo1.maven.org/maven2')) {
                    project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_REPOSITORY_URL."
                    remove repo
                }
                if (url.startsWith('https://jcenter.bintray.com/')) {
                    project.logger.lifecycle "Repository ${repo.url} replaced by $ALIYUN_JCENTER_URL."
                    remove repo
                }
            }
        }
        maven {
            url ALIYUN_REPOSITORY_URL
            url ALIYUN_JCENTER_URL
        }
    }
}

gradle <=> maven

1. gradle -> maven

build.gradle

apply plugin: 'java'
apply plugin: 'maven'

group = 'com.101tec'
version = '0.7-dev'
sourceCompatibility = 1.6

task writeNewPom << {
    pom {
        project {
            inceptionYear '2008'
            licenses {
                license {
                    name 'The Apache Software License, Version 2.0'
                    url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                    distribution 'repo'
                }
            }
        }
    }.writeTo("$buildDir/pom.xml")
}

2. maven -> gradle

gradle init --type pom