解析build.gradle文件
Gradle是一个非常先进的项目构建工具,它使用了一种基于Groovy的领域特定语言DSL来声明项目设置,摒弃了传统XML(如Ant和Maven)的各种繁琐配置
项目结构如上图:
1、最外层目录下的build.gradle文件(通常情况下不需要修改这个文件内容),代码如下所示:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
(1)这些代码都是自动生成的,两处repositories的闭包中都声明了jcenter()这行配置,jcenter是一个代码托管仓库,配置之后我们能够轻松引用任何jcenter上的开源项目。
(2)dependencies闭包中使用classpath声明了一个Gradle插件。最后面部分为插件版本号
2、app目录下的build.gradle文件,代码如下:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildeToolsVersion “24.0.2”
defaultConfig {
applicationId "com.example.kpp.test01"
minSdkVersion 15
targetSdkVersion 28
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(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:design:28.0.0-alpha3'
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'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.github.bumptech.glide:glide:3.8.0'
implementation 'com.google.zxing:zxing-parent:3.3.3'
implementation 'com.lzy.net:okhttputils:+'
compile 'org.xutils:xutils:3.5.0'
compile 'com.amap.api:3dmap:latest.integration'
compile 'com.amap.api:location:latest.integration'
}
(1)第一行应用了一个插件,一般有两种值可选:com.android.application表示是一个应用程序模块,com.android.library表示是一个库模块。应用程序模块和库模块的最大区别在于,一个是可以直接运行,一个只能作为代码库依附于别的应用程序模块来运行
(2)android闭包,这个闭包中可以配置项目构建的各种属性:
complieSdkVersion用于指定项目的编译版本,这个指定成24表示使用Android 7.0系统的SDK编译;
buildToolsVersion用于指定项目构建工具的版本,当前使用的是24.0.2;
android闭包中嵌套了一个defaultConfig闭包,defaultConfig闭包中可以对项目的更多细节进行配置:
applicationId用于指定项目的包名;
minSdkVersion用于指定项目最低兼容的Android版本,这里指定成15表示最低兼容到Android 4.0系统;
targetSdkVersion指定的值表示在该目标版本上已经做了充分的测试,系统将会为你的应用程序启用一些最新的功能和特性,如;
versionCode用于指定项目的版本号;
versionName用于指定项目的版本名;
testInstrumentationRunner表示采用的测试框架;
(3)buildType闭包用于指定生成安装文件的相关配置,通常只会有两个子闭包,一个是debug,一个是release。debug闭包用于指定生成测试版本安装文件的配置,release闭包用于指定生成正式版本安装文件的配置。
minifyEnabled用于指定是否对项目的代码进行混淆,true表示混淆,false表示不混淆;
proguardFile用于指定混淆时使用的规则文件,这里指定了两个文件,第一个proguard-android.txt是在Android SDK目录下的,里面是所有项目通用的混淆规则,第二个proguard-rules.pro是在当前项目的根目录下的,里面可以编写当前项目特有混淆规则。
(4)dependencies闭包,指定当前项目所有依赖。Android Studio项目共有3种依赖方式:本地依赖,库依赖和远程依赖。