当前位置:   article > 正文

android studio gradle配置详解

android studio gradle配置

原文出处

标题:Android studio gradle 版本 android studio gradle配置详解

作者:daleiwang

原文链接:Android studio gradle 版本 android studio gradle配置详解_daleiwang的技术博客_51CTO博客

.gradle 文件简单介绍

一个 Android Studio 项目中,会存在多个 .gradle 文件。其中, project 目录下存在一个 build.gradle 文件和一个 settings.gradle 文件;每一个 module 会存在一个 build.gradle 文件。

project中的build.gradle

  1. buildscript {
  2. repositories {
  3. jcenter()
  4. }
  5. dependencies {
  6. classpath 'com.android.tools.build:gradle:1.0.0'
  7. }
  8. }
  9. allprojects {
  10. repositories {
  11. jcenter()
  12. }
  13. }

默认的 project 目录下的 build.gradle 文件内容如上。

buildscript :用于设置驱动构建过程的代码。

jcenter():声明使用 maven 仓库。在老版本中,此处为 mavenCentral()。

mavenCentral() :表示依赖从 Central Maven 2 仓库中获取。

jcenter() :表示依赖从 Bintary’s JCenter Maven 仓库中获取。

mavenLocal() :表示依赖从本地的Maven仓库中获取。

dependencies :声明了使用 Android Studio gradle 插件版本。一般升级AS或者导入从Eclipse中生成的项目时需要修改下面gradle版本。具体的版本对应关系,请点击。

allprojects:设置每一个 module 的构建过程。在此例中,设置了每一个 module 使用 maven 仓库依赖。

settings.gradle

include ':app'

说明:

默认的 project 目录下的 settings.gradle 文件内容如上。可有可能默认情况下, project 目录下的 settings.gradle 文件不存在,你可以自己创建。

include ‘:app’:表示当前 project 下有一个名称为 app 的 module 。

如果你的一个 module 并不是 project 根目录下,你可以这么设置。

  1. include ':app2'
  2. project(':app2').projectDir = new File('path/to/app2')

Module中的build.gradle

  1. //设置脚本的运行环境
  2. buildscript {
  3. //支持java 依赖库管理(maven/ivy),用于项目的依赖。
  4. repositories {
  5. mavenCentral()
  6. }
  7. //依赖包的定义。支持maven/ivy,远程,本地库,也支持单文件
  8. dependencies {
  9. classpath 'com.android.tools.build:gradle:0.4'
  10. }
  11. }
  12. //声明构建的项目类型,这里当然是android了
  13. apply plugin: 'android'
  14. //设置编译android项目的参数
  15. android {
  16. compileSdkVersion 17
  17. buildToolsVersion "17"
  18. defaultConfig {
  19. minSdkVersion 8
  20. targetSdkVersion 17
  21. }
  22. //Android默认配置
  23. sourceSets {
  24. main {
  25. manifest.srcFile 'AndroidManifest.xml'
  26. java.srcDirs = ['src']
  27. resources.srcDirs = ['src']
  28. aidl.srcDirs = ['src']
  29. renderscript.srcDirs = ['src']
  30. res.srcDirs = ['res']
  31. assets.srcDirs = ['assets']
  32. }
  33. //测试所在的路径,这里假设是tests文件夹,没有可以不写这一行
  34. instrumentTest.setRoot('tests')
  35. }
  36. //这个是解决lint报错的代码
  37. lintOptions {
  38. abortOnError false
  39. }
  40. /**
  41. * 签名设置
  42. */
  43. signingConfigs {
  44. myConfigs {
  45. storeFile file("签名文件地址")
  46. keyAlias "..."
  47. keyPassword "..."
  48. storePassword "..."
  49. }
  50. }
  51. /**
  52. * 混淆设置
  53. */
  54. buildTypes {
  55. release {
  56. signingConfig signingConfigs.myConfigs
  57. runProguard true
  58. proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
  59. }
  60. }
  61. /**
  62. * 渠道打包(不同包名)
  63. */
  64. productFlavors {
  65. qqqq {
  66. applicationId = '包名'
  67. }
  68. hhhhh {
  69. applicationId='包名'
  70. }
  71. }
  72. }
  73. /**
  74. * .so文件的导入
  75. */
  76. task copyNativeLibs(type: Copy) {
  77. from fileTree(dir: 'libs', include: 'armeabi/*.so') into 'build/lib'
  78. }
  79. tasks.withType(Compile) {
  80. options.encoding = "UTF-8"
  81. }
  82. tasks.withType(Compile) {
  83. compileTask -> compileTask.dependsOn copyNativeLibs
  84. }
  85. clean.dependsOn 'cleanCopyNativeLibs'
  86. tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask ->
  87. pkgTask.jniFolders = [new File(buildDir, 'lib')]
  88. }
  89. //依赖库
  90. dependencies {
  91. compile fileTree(dir: 'libs', include: ['*.jar'])
  92. }

一些关键词说明:

android用来指定Android打包插件的相关属性,其包含如下节点

compileSdkVersion(apiLevel):设置编译时用的Android版本

buildToolsVersion(buildToolsVersionName):设置编译时使用的构建工具的版本

defaultConfig:设置一些默认属性,其可用属性是buildTypes和ProductFlavors之和

sourceSets:配置相关源文件的位置,当你的项目的目录结构跟默认的有区别但又不想改的时候sourceSets就派上用场了

– aidl 设置aidi的目录

– assets 设置assets资源目录

– compileConfigurationName The name of the compile configuration for this source set.

– java Java源代码目录

– jni JNI代码目录

– jniLibs 已编译好的JNI库目录

– manifest 指定清单文件

– name The name of this source set.

– packageConfigurationName The name of the runtime configuration for this source set.

– providedConfigurationName The name of the compiled-only configuration for this source set.

– renderscript Renderscript源代码目录

– res 资源目录

– setRoot(path) 根目录

signingConfigs:配置签名信息

– keyAlias 签名的别名

– keyPassword 密码

– storeFile 签名文件的路径

– storePassword 签名密码

– storeType 类型

buildTypes:配置构建类型,可打出不同类型的包,默认有debug和release两种,你还可以在增加N种

– applicationIdSuffix 修改applicationId,在默认applicationId的基础上加后缀。在buildType中修改applicationId时只能加后缀,不能完全修改

– debuggable 设置是否生成debug版的APK

– jniDebuggable 设置生成的APK是否支持调试本地代码

– minifyEnabled 设置是否执行混淆

– multiDexEnabled Whether Multi-Dex is enabled for this variant.

– renderscriptDebuggable 设置生成的APK是否支持调试RenderScript代码

– renderscriptOptimLevel 设置RenderScript优化级别

– signingConfig 设置签名信息

– versionNameSuffix 修改版本名称,在默认版本名称的基础上加后缀。在buildType中修改版本名称时只能加后缀,不能完全修改

– zipAlignEnabled 设置是否对APK包执行ZIP对齐优化

– proguardFile(proguardFile) 添加一个混淆文件

– proguardFiles(proguardFileArray) 添加多个混淆文件

– setProguardFiles(proguardFileIterable) 设置多个混淆文件

productFlavors:配置不同风格的APP,在buildTypes的基础上还可以让每一个类型的APP拥有不同的风格,所以最终打出的APK的数量就是buildTypes乘以productFlavors

– applicationId 设置应用ID

– multiDexEnabled Whether Multi-Dex is enabled for this variant.signingConfig Signing config used by this product flavor.

– testApplicationId 设置测试时的应用ID

– testFunctionalTest See instrumentation.

– testHandleProfiling See instrumentation.

– testInstrumentationRunner Test instrumentation runner class name.

– versionCode 设置版本号

– versionName 设置版本名称

– minSdkVersion(int minSdkVersion) 设置兼容的最小SDK版本

– minSdkVersion(String minSdkVersion) 设置兼容的最小版本

– proguardFile(proguardFile) 添加一个混淆文件

– proguardFiles(proguardFileArray) 添加多个混淆文件

– setProguardFiles(proguardFileIterable) 设置多个混淆文件

– targetSdkVersion(int targetSdkVersion) 设置目标SDK版本

– targetSdkVersion(String targetSdkVersion) 设置目标SDK版本

testOptions:设置测试相关属性

– reportDir 设置测试报告的目录

– resultsDir 设置测试结果的目录

– aaptOptions:设置AAPT的属性

– failOnMissingConfigEntry Forces aapt to return an error if it fails to find an entry for a configuration.

– ignoreAssets Pattern describing assets to be ignore.

– noCompress Extensions of files that will not be stored compressed in the APK.

– useNewCruncher Whether to use the new cruncher.

lintOptions:设置Lint的属性

– abortOnError 设置是否在lint发生错误时终止构建

– absolutePaths Whether lint should display full paths in the error output. By default the paths are relative to the path lint was invoked from.

– check The exact set of issues to check, or null to run the issues that are enabled by default plus any issues enabled via LintOptions.getEnable() and without issues disabled via LintOptions.getDisable(). If non-null, callers are allowed to modify this collection.

– checkAllWarnings Returns whether lint should check all warnings, including those off by default.

– checkReleaseBuilds Returns whether lint should check for fatal errors during release builds. Default is true. If issues with severity “fatal” are found, the release build is aborted.

– disable The set of issue id’s to suppress. Callers are allowed to modify this collection.

– enable The set of issue id’s to enable. Callers are allowed to modify this collection. To enable a given issue, add the issue ID to the returned set.

– explainIssues Returns whether lint should include explanations for issue errors. (Note that HTML and XML reports intentionally do this – – – unconditionally, ignoring this setting.)

– htmlOutput The optional path to where an HTML report should be written.

– htmlReport Whether we should write an HTML report. Default true. The location can be controlled by LintOptions.getHtmlOutput().

– ignoreWarnings Returns whether lint will only check for errors (ignoring warnings).

– lintConfig The default configuration file to use as a fallback.

– noLines Whether lint should include the source lines in the output where errors occurred (true by default).

– quiet Returns whether lint should be quiet (for example, not write informational messages such as paths to report files written).

– severityOverrides An optional map of severity overrides. The map maps from issue id’s to the corresponding severity to use, which must be – “fatal”, “error”, “warning”, or “ignore”.

– showAll Returns whether lint should include all output (e.g. include all alternate locations, not truncating long messages, etc.)

– textOutput The optional path to where a text report should be written. The special value “stdout” can be used to point to standard output.

– textReport Whether we should write an text report. Default false. The location can be controlled by LintOptions.getTextOutput().

– warningsAsErrors Returns whether lint should treat all warnings as errors.

– xmlOutput The optional path to where an XML report should be written.

– xmlReport Whether we should write an XML report. Default true. The location can be controlled by LintOptions.getXmlOutput().

– check(id) Adds the id to the set of issues to check.

– check(ids) Adds the ids to the set of issues to check.

– disable(id) Adds the id to the set of issues to enable.

– disable(ids) Adds the ids to the set of issues to enable.

– enable(id) Adds the id to the set of issues to enable.

– enable(ids) Adds the ids to the set of issues to enable.

– error(id) Adds a severity override for the given issues.

– error(ids) Adds a severity override for the given issues.

– fatal(id) Adds a severity override for the given issues.

– fatal(ids) Adds a severity override for the given issues.

– ignore(id) Adds a severity override for the given issues.

– ignore(ids) Adds a severity override for the given issues.

– warning(id) Adds a severity override for the given issues.

– warning(ids) Adds a severity override for the given issues.

dexOptions

– incremental Whether to enable the incremental mode for dx. This has many limitations and may not work. Use carefully.

– javaMaxHeapSize Sets the -JXmx* value when calling dx. Format should follow the 1024M pattern.

– jumboMode Enable jumbo mode in dx (–force-jumbo).

– preDexLibraries Whether to pre-dex libraries. This can improve incremental builds, but clean builds may be slower.

compileOptions:设置编译的相关属性

– sourceCompatibility Language level of the source code.

– targetCompatibility Version of the generated Java bytecode.

packagingOptions:设置APK包的相关属性

– excludes The list of excluded paths.

– pickFirsts The list of paths where the first occurrence is packaged in the APK.

– exclude(path) Adds an excluded paths.

– pickFirst(path) Adds a firstPick path. First pick paths do get packaged in the APK, but only the first occurrence gets packaged.

– jacoco:设置JaCoCo的相关属性

– version 设置JaCoCo的版本

splits:设置如何拆分APK(比如你想拆分成arm版和x86版)

– abi ABI settings.

– abiFilters The list of ABI filters used for multi-apk.

– density Density settings.

– densityFilters The list of Density filters used for multi-apk.

dependencies:配置依赖

本地依赖

gradle 作为构建工具,能够很方便的使用本地jar包,以下为使用的代码块。

  1. dependencies {
  2. //单文件依赖
  3. compile files('libs/android-support-v4.jar')
  4. //某个文件夹下面全部依赖
  5. compile fileTree(dir: 'libs', include: '*.jar')
  6. }
  7. android {
  8. }

远程依赖

gradle 同时支持maven,ivy,由于ivy我没用过,所以用maven 作为例子,以下为代码块:

  1. repositories {
  2. //从中央库里面获取依赖
  3. mavenCentral()
  4. //或者使用指定的本地maven 库
  5. maven{
  6. url "file://F:/githubrepo/releases"
  7. }
  8. //或者使用指定的远程maven库
  9. maven{
  10. url "远程库地址"
  11. }
  12. }
  13. dependencies {
  14. //应用格式: packageName:artifactId:version
  15. compile 'com.google.android:support-v4:r13'}
  16. android {
  17. }

android library 依赖

对于项目依赖 android library的话,就不是依赖一个jar,那么简单了,在这里需要使用gradle mulit project 机制。在过去,android library并没有一个很好的包管理方式,简单来说,在gradle出现以前,官方并没有一种用于管理android library 依赖包的方式,一般我们都是直接下载别人的android library project 源码进行集成,而对于第三方的android-maven-plugin 用的是apklib 格式。

而现在,官方终于推出一种android library的打包格式,扩展名为.aar。前面提到,目前android gradle插件并不支持本地直接使用.aar文件,不过,支持包管理库的引用方式,下面,我为大家说一下,怎么对android library 发布使用。

打包android library

对android library 进行打包直接在library项目下面使用gradle build 即可,然后,你就会在 build/libs 目录下看到两个*.aar文件,一个debug包用的,一个是release 下用的,看个人需求使用,这里我们用的是release 版本的 .aar 文件。

引用脚本跟前面讲的依赖库相似

  1. dependencies {
  2. compile(name: 'pulltorefresh', ext: 'aar')
  3. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/597880
推荐阅读
相关标签
  

闽ICP备14008679号