dependencies { }

  • implementation:依赖的库只能在本项目使用,外部无法使用。比如我在一个 libiary 中使用 implementation 依赖了 gson 库,然后我的主项目依赖了 libiary,那么,我的主项目就无法访问 gson 库中的方法。这样的好处是编译速度会加快,推荐使用 implementation 的方式去依赖,如果你需要提供给外部访问,那么就使用 api 依赖即可
  • api(compile):使用该方式依赖的库将会参与编译和打包
  • testImplementation(testCompile):只在单元测试代码的编译以及最终打包测试 Apk 时有效
  • debugImplementation(debugCompile):只在 debug 模式的编译和最终的 debug Apk 打包时有效
  • releaseImplementation(releaseCompile):仅仅针对 Release 模式的编译和最终的 Release Apk 打包
  • compileOnly(provided):只在编译时有效,不会参与打包,可以在自己的moudle中使用该方式依赖。比如 com.android.support,gson 这些使用者常用的库,避免冲突。
  • runtimeOnly(apk):只在生成 Apk 的时候参与打包,编译时不会参与,很少用。

在实际项目开发中,我们会引入很多第三方开源库,自然就会造成依赖冲突,这里就涉及到在 dependencies 提供的配置字段:

  • force = true:即使在有依赖库版本冲突的情况下坚持使用被标注的这个依赖库版本
  • transitive = true:依赖的依赖是否可用,举个例子,使用的三方库中可能也依赖别的库,我们称之为“间接依赖”
  • exclude:用于排除指定版本库,通常用于排除冲突依赖库
dependencies {
    compile('com.sensorsdata.analytics.android:SensorsAnalyticsSDK:2.0.2'{
            //强制使用我们依赖的 2.0.2 版本库
            force = true
            //剔除间接依赖的库,可以通过这三种方式
            exclude module: 'cglib' //by artifact name
            exclude group: 'org.jmock' //by group
            exclude group: 'org.unwanted', module: 'iAmBuggy' //by both name and group
            //禁用所有的间接依赖库
            transitive = false
        }
}

repositories { }

配置 Project 项目所需的仓库地址,Gradle 必须知道从哪里下载外部依赖,这是由仓库配置来指定的,比如 google()、jcenter() 或 mavenCentral()。通常在 buildscript 脚本块中也能看到配置的 repositories 属性,buildscript 中的声明是 gradle 脚本自身需要使用的资源,可以声明的资源包括依赖项、 第三方插件、 maven 仓库地址等。而在 build.gradle 文件中直接声明的依赖项、仓库地址等信息是项目自身需要的资源。

repositories {
    //Maven本地仓库,寻找本地仓库的逻辑与Maven相同
    mavenLocal()
    //Maven中心仓库
    mavenCentral()
    //JCenter仓库
    jcenter()
    //其它Maven远程仓库
    maven {
        //可以指定身份验证信息
        credentials {
            username 'user'
            password 'password'
        }
        url "http://repo.mycompany.com/maven2"
        //如果上面的URL找不到构件,则在下面找
        artifactUrls "http://repo.mycompany.com/jars"
    }
    //Ivy远程仓库
    ivy {
        url "http://repo.mycompany.com/repo"
    }
    //Ivy本地仓库
    ivy {
        url "../local-repo"
    }
    //扁平布局的文件系统仓库
    flatDir {
        dirs 'lib'
    }
    flatDir {
        dirs 'lib1', 'lib2'
    }
}

buildTypes {}

当前项目的构建类型配置,对应的配置类型 BuildType 类,在 Android Studio 的中已经给我们内置了 release 和 debug 两种构建类型,这两种模式的主要差异在于能否在设备上调试以及签名不一样,这里会涉及到很多属性可以配置。

  • applicationIdSuffix:配置基于应用默认的 applicationId 的后缀,常用于构建变体应用。
  • consumerProguardFiles:配置 .aar 文件中是否使用 Proguard 混淆。
  • crunchPngs:针对 png 的优化,设置为 true 的时候会增加编译时间。
  • debuggable:配置构建的 apk 是否能够进行 debug。
  • javaCompileOptions:配置 Java 编译的配置
  • jniDebuggable:配置构建类型的 apk native code 是否能够进行 debug。
  • minifyEnabled:是否启用 Proguard 混淆。
  • multiDexEnabled:是否使用分包。
  • multiDexKeepFile:指定放到主 dex 中的文件。
  • multiDexKeepProguard:配置指定的文件使用 Proguard。
  • proguardFiles:混淆文件。
  • shrinkResources:用于配置是否自动清理未使用的资源,默认为 false。
  • signingConfig:签名文件。
  • useProguard
  • versionNameSuffix:类似于 applicationIdSuffix。
  • zipAlignEnabled:zipAlign 优化 apk 文件的工具。
buildTypes {
    release {
        minifyEnabled false
        crunchPngs true
        debuggable false
        shrinkResources true
        multiDexEnabled true
        multiDexKeepProguard file('proguard-rules.pro') // keep specific classes using proguard syntax
        multiDexKeepFile file('multiDexKeep.txt')
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig
        zipAlignEnabled true
        applicationIdSuffix '.release'
        versionNameSuffix '.release'
    }
    debug {
        applicationIdSuffix '.debug'
        versionNameSuffix '.debug'
    }
}

defaultConfig {}

defaultConfig 也是 Android 插件中常见的一个配置块,负责默认的所有配置。同样它是一个 ProductFlavor,如果一个 ProductFlavor 没有被特殊配置,则默认使用 defaultFlavor 的配置,比如报名、版本号、版本名称等。常见的属性有:

  • applicationId:applicationId 是 ProductFlavor 的一个属性,用于配置 App 生成的进程名,默认情况下是 null。
  • minSdkVersion:指定 Apk 支持的最低 Android 操作系统版本。
  • targetSdkVersion:用于配置 Apk 基于的 SDK 哪个版本进行开发。
  • versionCode:同样是 ProductFlavor 的一个属性,配置 Apk 的内部版本号。
  • versionName:配置版本名称。
  • testApplicationId:配置测试 App 的报名,默认情况下是 applicationId + ".test"。
  • testInstrumentationRunner:配置单元测试使用的 Runner,默认是android.test.InstrumentationTestRunner,或者可以使用自定义的 Runner。
  • signingConfig:配置默认的签名信息,对生成的 App 签名。
  • proguardFile:用于配置使用的混淆文件。
  • proguardFiles:配置混淆使用的文件,可以配置多个。
defaultConfig {
    applicationId 'com.andoter.dsw'
    minSdkVersion 15
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    signingConfigs signingConfigs.release
}

dexOptions { }

dex 的配置项,通常在开发的过程中,我们可以通过配置 dexOptions {} 提高编译速度,与之对应的是 DexOptions 接口,该接口由 DefaultDexOptions 默认实现,DefaultDexOptions 类中包含以下属性:

  • preDexLibraries:默认 true
  • jumboMode:默认 false
  • dexInProcess:默认为 true,所有的 dex 都在 process 中,提高效率
  • javaMaxHeapSize:最大的堆大小
  • maxProcessCount:最大的 process 个数
  • threadCount:线程个数
dexOptions {
    incremental true //是否增量,如果开启multi-dex, 此句无效
    preDexLibraries true
    javaMaxHeapSize "4g" //java 编译的 Heap 大小
    jumboMode true
    threadCount 8 //gradle输就输在了并行上, 都是串行, 增加线程数没用
    // 设置最大的进程数:Memory = maxProcessCount * javaMaxHeapSize
    maxProcessCount 8
}

lintOptions { }

Lint 是Android Studio 提供的 代码扫描分析工具,它可以帮助我们发现代码结构/质量问题,同时提供一些解决方案,而且这个过程不需要我们手写测试用例。Lint 发现的每个问题都有描述信息和等级(和测试发现 bug 很相似),我们可以很方便地定位问题同时按照严重程度
进行解决。

android {
    lintOptions {
        // true--关闭lint报告的分析进度
        quiet true
        // true--错误发生后停止gradle构建
        abortOnError false
        // true--只报告error
        ignoreWarnings true
        // true--忽略有错误的文件的全/绝对路径(默认是true)
        //absolutePaths true
        // true--检查所有问题点,包含其他默认关闭项
        checkAllWarnings true
        // true--所有warning当做error
        warningsAsErrors true
        // 关闭指定问题检查
        disable 'TypographyFractions','TypographyQuotes'
        // 打开指定问题检查
        enable 'RtlHardcoded','RtlCompat', 'RtlEnabled'
        // 仅检查指定问题
        check 'NewApi', 'InlinedApi'
        // true--error输出文件不包含源码行号
        noLines true
        // true--显示错误的所有发生位置,不截取
        showAll true
        // 回退lint设置(默认规则)
        lintConfig file("default-lint.xml")
        // true--生成txt格式报告(默认false)
        textReport true
        // 重定向输出;可以是文件或'stdout'
        textOutput 'stdout'
        // true--生成XML格式报告
        xmlReport false
        // 指定xml报告文档(默认lint-results.xml)
        xmlOutput file("lint-report.xml")
        // true--生成HTML报告(带问题解释,源码位置,等)
        htmlReport true
        // html报告可选路径(构建器默认是lint-results.html )
        htmlOutput file("lint-report.html")
        //  true--所有正式版构建执行规则生成崩溃的lint检查,如果有崩溃问题将停止构建
        checkReleaseBuilds true
        // 在发布版本编译时检查(即使不包含lint目标),指定问题的规则生成崩溃
        fatal 'NewApi', 'InlineApi'
        // 指定问题的规则生成错误
        error 'Wakelock', 'TextViewEdits'
        // 指定问题的规则生成警告
        warning 'ResourceAsColor'
        // 忽略指定问题的规则(同关闭检查)
        ignore 'TypographyQuotes'
    }
}

productFlavors { }

用于构建不同的产品风味,在上面我们提到 defaultConfig{} 也是一种产品风味,可作为所有产品风味的“基类”共同部分。风味(Flavor) 对应 ProductFlavor 类,该类的属性与配置属性相匹配。

android {
    ...
    defaultConfig {...}
    buildTypes {...}
    productFlavors {
        demo {
            applicationIdSuffix ".demo"
            versionNameSuffix "-demo"
        }
        full {
            applicationIdSuffix ".full"
            versionNameSuffix "-full"
        }
    }
}

signingConfigs { }

配置签名信息,常用于 BuildType 和 ProductFlavor 配置,在构建变体的过程中,会出现很多种类,所以针对不同类别的变体所使用的签名可能也是不同的,这就需要使用 signingConfigs{} 配置签名信息合集,然后按需所取。


signingConfigs {
    release {//发布版本的签名配置
      storeFile file(props['KEYSTORE_FILE'])
      keyAlias props['KEY_ALIAS']
      storePassword props['KEYSTORE_PWD']
      keyPassword props['KEY_PWD']
    }
    debug {//调试版本的签名配置
      storeFile file(props['DEBUG_KEYSTORE'])
      keyAlias props['DEBUG_ALIAS']
      storePassword props['DEBUG_KEYSTORE_PWD']
      keyPassword props['DEBUG_KEY_PWD']
    }
}

buildTypes {
    signingConfig signingConfigs.release
}

sourceSets { }

在 AndroidStudio 中,在 src/main/java 目录下创建我们的 .java 文件,这些都是系统通过 sourceSet{} 设置好的,比如我们在外部创建一个文件夹,选中文件夹右键就无创建 .java 文件的选项。就需要我们通过 sourceSets 进行配置,脚本块对应 AndroidSourceSet 接口,接口中有:

  • AndroidSourceSet java(Closure configureClosure):配置 java 文件存放路径
  • AndroidSourceSet resources(Closure configureClosure):配置 resource 目录
  • AndroidSourceSet jniLibs(Closure configureClosure):配置 jniLibs 目录
  • AndroidSourceSet jni(Closure configureClosure):配置 jni 文件目录
  • AndroidSourceSet renderscript(Closure configureClosure):配置 renderscript 目录
  • AndroidSourceSet aidl(Closure configureClosure):配置 aidl 文件目录
  • AndroidSourceSet assets(Closure configureClosure):配置 assets 目录
  • AndroidSourceSet res(Closure configureClosure):配置 res 目录
  • AndroidSourceSet manifest(Closure configureClosure):配置 manifest 目录
sourceSets {
    main {
        java {
            srcDir 'src/main/testjava'
        }
        resources {
            srcDir 'src/resources'
        }
    }
}

更完整的教程 https://www.jianshu.com/p/4fbf352ffc56

深入学习 Gradle学习笔记

最后修改日期:2019年12月4日

作者

留言

撰写回覆或留言