分享

gradle实践系列:android gradle插件(1) | 牛头码农

 oskycar 2017-11-02

gradle实践系列:android gradle插件(1)

2017.01.13 hucaihua programming

一. android gradle插件基础

1.插件概览

android studio新建一个工程,我们能看到studio默认给生成了三个重要的gradle文件,如图所示:
image

1) setting.gradle

include ':app'

这个include语句表示项目包含的子目录,如果我们引用了其他模块或者库,也会显示在后面,例如,我们引用了ox库,那么setting.gradle是这样的

include ':app','ox'

2).根目录下的build.gradle

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

gradle 默认是没有集成android-gradle插件的,google公司开发并提供了这个anroid-gradle插件,第一行的buildscript语句块告知gradle脚本从哪里去下载android-gradle插件

Jcenter 是一个类似于mavenCentral的资源仓库,它使用CDN进行分发,速度相对较快,并且使用htttps进行传输。

allprojects语句块表示,如果没有特别的申明,后续依赖的库默认使用的仓库位置

task语句块定义了一个新的任务,这个任务的作用是删除编译过程中产生的文件。这个任务可以在gradle构建中被调用。

3). app 目录下的build.gradle

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.hch.babyenglish"
minSdkVersion 15
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile project(':ox')
}

apply plugin语句将android-gradle插件添加到构建系统,这样就可以在gradle文件中使用android-gradle定义好的属性和方法。android-gradle插件的唯一标识是com.android.application。

dependencies语句块申明了构建过程中依赖的库。fileTree表示将app目录下的libs目录中所有jar文件添加到classpath;project表示构建app前需要先构建ox,也就是app构建依赖于ox库的构建

android语句块申明了一些常用的构建属性值,它的所有属性由android DSL定义

  • compileSdkVersion 编译android项目使用的SDK版本
  • buildToolsVersion build工具版本
  • applicationId 包名
  • minSdkVersion 最低兼容SDK版本
  • targetSdkVersion 目标SDK版本
  • versioncode app版本号,用于升级
  • versionname app版本信息,用于显示
  • buildTypes 打包时候混淆相关

关于compileSdkVerison , targetSdkVersion , minSdkVersion区别可以参考 :

compileSdkVersion , targetSdkVersion 和 minSdkVersion

android studio 提供了gradle tool插件,可以用图形化的方式编辑这些属性。

image

image

关于gradle 版本 和 gradle tool版本关系,可以参考:

Gradle版本管理-升级与降级

2.执行gradle构建

我们不需要手动去安装gradleandroid-gradle插件提供了gradle-wrapper去解决gradle下载和构建版本一致性问题。

image

gradle-wrapper.properties内容一般如下:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

distributionUrl表示从哪个地址去下载app构建需要的gradle版本;zipStoreBase表示下载的gradle会被存放于哪个目录下;zipStorePath表示gradle会存放于zipStoreBase+zipStorePath下。

部分童鞋可能会下载比较慢,为了加快速度,我们可以指定distributionUrl为本地路径:

#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=file\:/C\:/d/soft/develop/gradle-2.14.1-all.zip

打开android studio的自带终端

image

执行以下命令,可以开始构建过程

gradlew build

第一次构建会下载指定版本的gradle,这个时间大约5-10分钟,再次构建就会使用缓存的gradle,或者可以直接修改gradle-wrapper.properties,指定使用本地的gradle,省去下载时间。

构建完成,我们在app/build目录下能看到编译完的代码,在app/build/outpus/apk 目录下能看到生成的apk。

除了gradlew build命令,我们也可以运行其他的任务,通过以下命令可以查看支持的任务列表

gradle -q tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Android tasks
-------------
androidDependencies - Displays the Android dependencies of the project.
signingReport - Displays the signing info for each variant.
sourceSets - Prints out all the source sets defined in this project.
Build tasks
-----------
assemble - Assembles all variants of all applications and secondary packages.
assembleAndroidTest - Assembles all the Test applications.
assembleDebug - Assembles all Debug builds.
assembleRelease - Assembles all Release builds.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend
buildNeeded - Assembles and tests this project and all projects it depends on.
clean - Deletes the build directory.
compileDebugAndroidTestSources
compileDebugSources
compileDebugUnitTestSources
compileReleaseSources
compileReleaseUnitTestSources
extractDebugAnnotations - Extracts Android annotations for the debug variant int
extractReleaseAnnotations - Extracts Android annotations for the release variant
mockableAndroidJar - Creates a version of android.jar that's suitable for unit t
Build Setup tasks
-----------------
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root projec
components - Displays the components produced by root project 'client'. [incubat
dependencies - Displays all dependencies declared in root project 'client'.
dependencyInsight - Displays the insight into a specific dependency in root proj
help - Displays a help message.
model - Displays the configuration model of root project 'client'. [incubating]
projects - Displays the sub-projects of root project 'client'.
properties - Displays the properties of root project 'client'.
tasks - Displays the tasks runnable from root project 'client' (some of the disp
Install tasks
-------------
installDebug - Installs the Debug build.
installDebugAndroidTest - Installs the android (on device) tests for the Debug b
uninstallAll - Uninstall all applications.
uninstallDebug - Uninstalls the Debug build.
uninstallDebugAndroidTest - Uninstalls the android (on device) tests for the Deb
uninstallRelease - Uninstalls the Release build.
Verification tasks
------------------
check - Runs all checks.
connectedAndroidTest - Installs and runs instrumentation tests for all flavors o
connectedCheck - Runs all device checks on currently connected devices.
connectedDebugAndroidTest - Installs and runs the tests for debug on connected d
deviceAndroidTest - Installs and runs instrumentation tests using all Device Pro
deviceCheck - Runs all device checks using Device Providers and Test Servers.
lint - Runs lint on all variants.
lintDebug - Runs lint on the Debug build.
lintRelease - Runs lint on the Release build.
test - Run unit tests for all variants.
testDebugUnitTest - Run unit tests for the debug build.
testReleaseUnitTest - Run unit tests for the release build.
Other tasks
-----------
assembleDefault
clean
compileRetrolambdaDebug
compileRetrolambdaDebugAndroidTest
compileRetrolambdaRelease
extractProguardFiles
jarDebugClasses
jarReleaseClasses
transformResourcesWithMergeJavaResForDebugUnitTest
transformResourcesWithMergeJavaResForReleaseUnitTest

可以同时运行几个gradle任务,任务之间使用空格分开,同一个任务在一次构建中只会执行一次。

gradlew lint assembleDebug

可以使用-x 参数,从任务中剔除其它任务。如:

gradlew assembleDebug -x lintDebug

执行任务还可以使用缩写的形式进行,如

gradlew androidDependencies

可以写成

gradlew anDe

gradle默认的构建脚本文件名是build.gradle,如果使用其它名字,在构建的时候用-b参数指定

gradlew -b myBuildFileName

android studio中,view - tool windows - gradle,打开gradle projects,我们能看到所有的gradle tasks

image

双击任意task,即可运行该task,运行结果显示在gradle console中

image

3.添加Java库依赖

添加依赖有两种方式,直接修改gradle文件或者通过android studio提供的可视化插件

1.修改gradle文件添加依赖

在app或者module的build.gradle中,dependencies块用于添加依赖的java库或者模块。

每一条依赖都与一项android配置有关,android-gradle插件默认提供的配置包括

  • compile
  • testCompile
  • runtime
  • testRuntime

依赖的库由 group:name:version三部分组成

compile 'com.google.code.gson:gson:2.6.2'

它等价于

compile group:'com.google.code',name:'gson',version:'2.6.2'

版本号的配置支持(不推荐)使用+号代表一系列版本

compile 'com.google.code.gson:gson:2.+'

如果要添加一系列的jar包,可以使用files或者fileTree

dependencies{
compile files('libs/a.jar','libs/b.jar')
compile fileTree(dir:'libs', include:'*.jar')
}

当我们修改了gradle文件,android studio会检测到,并提示需要同步

image

同步会针对修改去下载新增加的依赖库,或者进行其它变化的操作。

2.android studio添加依赖

右键app模块 - open module setting - 选中app - dependencies。
右侧的小箭头里可以指定依赖的配置项,默认是compile

image

点击+号在弹出的对话框里面输入想添加的库,如gson,选择其中一个,该依赖项会被加入到对应的配置项中。

image

image

4.指定依赖仓库地址

repositories用于指定仓库地址
常见的仓库包括
jcenter: https://jcenter.
mavenCentral: http://repo1./maven2

使用本地maven仓库

repositories {
mavenLocal()
mavenCentral()
}

指定maven仓库地址

repositories {
maven {
url 'http://repo./milestone'
}
}

指定maven仓库的身份验证信息

repositories {
maven {
credentials {
username 'username'
password 'password'
}
url 'http://repo./maven2'
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多