Android学习笔记之build.gradle

AndroidStudio是采用Gradle来构建项目的。gradle使用了一种基于Groovy的领域特定语音(DSL)来声明项目设置,摒弃了传统的基于XML的繁琐配置(例如:用Ant来构建项目)。

用AS创建一个项目之后,会看到有两个build.gradle文件。一个是在最外层目录下的,一个是在app目录下的。

最外层目录下的build.gradle文件结构如下:

buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

可以看到repositories的闭包中都声明了googe()和jcenter(),这两行代码都是代码库,声明了这两行配置之后,我们就可以在项目中使用google和jcenter上的开源项目了。其次,dependencies的闭包中使用classpath声明了一个gradle插件。

再看下app目录下的build.gradle文件,其结构如下:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId ""
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

首先,第一行apply plugin应用了一个插件,值为'com.android.application',说明这是一个应用程序模块,可以直接运行。还有一种值是'com.android.library',声明这是一个库模块,需要依附于别的应用程序模块来运行。

接下来,android闭包中,compileSdkVersion指定了该项目的编译版本。在defaultConfig子闭包中,applicationId指定了项目的包名,我们创建项目的时候就指定了包名,如果后续需要更改,就在该处进行更改即可。minSdkVersion是最低兼容的Android系统版本,15表示最低兼容到Android4.0系统。targetSdkVersion表示已经在该目标版本上进行了充分的测试,系统将会为该应用程序启用一些新版本的特性和功能。versionCode和versionName分别用来指定项目的版本号和版本名。

buildTypes闭包中用于指定生成安装文件的相关配置。通常有两个子闭包,除了上面的release还有个debug。release闭包用于指定生成正式版安装文件的配置,debug闭包则用于指定生成测试版安装文件的配置。minifyEnabled用于声明是否对项目代码进行混淆,true表示混淆。proguardFiles用于指定混淆时使用的规则文件,在这里指定了两个文件。其中,proguard-android.txt是在Android SDK目录下的,里面是所有项目通用的混淆规则;proguard-rules.pro是在当前项目的根目录下的,里面是当前项目特有的混淆规则。

最后的dependencies闭包用来指定当前项目的依赖关系。通常而言,Android项目一共有三种依赖方式:本地依赖,远程依赖,库依赖。在dependencies闭包中 implementation fileTree(dir: 'libs', include: ['*.jar'])即是本地依赖,它表明libs目录下所有.jar后缀的文件都添加到项目的构建路径中。 implementation 'com.android.support:appcompat-v7:27.1.1' 以及 implementation 'com.android.support.constraint:constraint-layout:1.1.2'都是远程依赖声明。以implementation 'com.android.support:appcompat-v7:27.1.1'为例,com.android.support是域名,appcompat-v7是组名称,27.1.1为版本号。

猜你喜欢

转载自blog.csdn.net/ein3614/article/details/81084627