4.3 初识Android Studio中的Gradle

来源:互联网 发布:pg数据库是什么 编辑:程序博客网 时间:2024/06/05 06:19

联系方式:

简书:WillFlow
CSDN:WillFlow
微信公众号:WillFlow

一、什么是Gradle?

Gradle是一种依赖管理工具,基于Groovy语言,面向Java应用为主,它抛弃了基于XML的各种繁琐配置,取而代之的是一种基于Groovy的内部领域特定(DSL)语言。

Android中使用Gradle Wrapper对Gradle进行了一层包装,这么做的原因可能是因为gradle更新速度实在太快,为了兼容性着想,才做了这么一套方案。
Gradle Scripts 目录结构

二、各文件解析

Hello World项目中的各个.gradle文件并没有很全,不过gradle文件的大体结构都是相似的,下面给出更全的.gradle文件内容并加以解释:

1、build.gradle(Module:app)

// 声明是Android程序apply plugin: 'com.android.application'android {    // 编译SDK的版本    compileSdkVersion 24    // build tools的版本    buildToolsVersion "24.0.1"    defaultConfig {        // 应用的包名        applicationId "com.example.wgh.helloworld"        minSdkVersion 18        targetSdkVersion 24        versionCode 1        versionName "1.0"        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"    }    // java版本    compileOptions {        sourceCompatibility JavaVersion.VERSION_1_7        targetCompatibility JavaVersion.VERSION_1_7    }    buildTypes {        debug {            // debug模式        }        release {            // 是否进行混淆            minifyEnabled false            // 混淆文件的位置            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'        }    }    // 移除lint检查的error    lintOptions {      abortOnError false    }}dependencies {    // 编译libs目录下的所有jar包    compile fileTree(dir: 'libs', include: ['*.jar'])    compile 'com.android.support:support-v4:21.0.2'    compile 'com.etsy.android.grid:library:1.0.5'    compile 'com.alexvasilkov:foldable-layout:1.0.1'    // 编译extras目录下的ShimmerAndroid模块    compile project(':extras:ShimmerAndroid')}
  • ### apply plugin
    是最新gradle版本的写法,以前的写法是apply plugin: ‘android’, 如果还是以前的写法,一定要改正过来。
  • ### buildToolsVersion
    这个需要我们本地安装该版本才行,很多人导入新的第三方库,失败的原因之一是build version的版本不对,这个可以手动更改成你本地已有的版本或者打开SDK Manager去下载对应版本。
  • ### applicationId
    代表应用的包名,也是最新的写法,这里就不再多说了。
  • ### minifyEnabled
    也是最新的语法,很早之前是runProguard,这个也需要更新下。
  • ### proguardFiles
    这部分有两段,前一部分代表系统默认的android程序的混淆文件,该文件已经包含了基本的混淆声明,免去了我们很多事,这个文件的目录在

2、build.gradle(Project:HelloWorld)

// Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.2.0'        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}allprojects {    repositories {        jcenter()    }}task clean(type: Delete) {    delete rootProject.buildDir}

这个文件是整个项目的gradle基础配置文件,主要包含了两个方面:一个是声明仓库的源,这里可以看到是指明的jcenter(),之前版本则是mavenCentral(),jcenter可以理解成是一个新的中央远程仓库,兼容maven中心仓库,而且性能更优,另一个则是声明了android gradle plugin的版本。

3、settings.gradle

这个文件是全局的项目配置文件,里面主要声明一些需要加入gradle的module:

include ':app'

文件中的app指的就是module,如果还有其他module的话,都需要按照这样的格式添加进去。

以上文件里的内容只是基本配置,其实还有很多自定义部分,如自动打包debug,release,beta等环境,签名,多渠道打包等,后续还会继续讲解,请继续关注。

微信公众号:WillFlow