Android studio 中 gradle 的使用
当我们创建一个新的工程,Android studio 会默认为我们创建三个 gradle 文件:两个 build.gradle 文件和一个 settings.gradle 文件。settings.gradle 文件位于项目根目录下,而 build.gradle 分别放在了根目录和 moudle 目录下。
下面是gradle文件的构成图:
MyApp
├── build.gradle
├── settings.gradle
└── app
└── build.gradle
这三个文件都是做什么的呢?
setting.gradle 解析
当你的 APP 刚刚创建时,这时只有一个模块,setting.gradle 将会是这样子的:
include ':app'
rootProject.name = "SimpleDemo"
setting.gradle文件将会在初始化时期执行。
根目录的build.gradle
该 gradle 文件是定义在这个工程下的所有模块的公共属性,它默认包含二个方法:
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
buildscript 方法是定义了全局的相关属性,repositories 定义了 jcenter 作为仓库。一个仓库代表着你的依赖包的来源,例如 maven 仓库。dependencies 用来定义构建过程。这意味着你不应该在该方法体内定义子模块的依赖包,你仅仅需要定义默认的 Android 插件就可以了,因为该插件可以让你执行相关 Android 的 tasks。
allprojects 方法可以用来定义各个模块(Module)的默认属性,你可以不仅仅局限于默认的配置,未来你可以自己创造 tasks 在 allprojects 方法体内,这些 tasks 将会在所有模块(Module)中可见。
模块内的 build.gradle
模块(Module)内的 gradle 文件只对该模块起作用,而且其可以重写任何的参数来自于根目录下的 gradle 文件。
示例:
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.budaye.simpledemo"//该属性复写了AndroidManifest文件中的包名
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
1. 第一行是 Android 应用插件
它是 google 的 Android 开发团队编写的插件,能够提供所有关于 Android 应用和依赖库的构建,打包和测试。
2. Android 方法
该方法包含了所有的 Android 属性,而唯一必须得属性为 compileSdkVersion(编译该app时候,你想使用到的 api 版本)和 buildToolsVersion(构建工具的版本号)。
defaultConfig 方法包含了该 app 的核心属性,该属性会重写在 AndroidManifest.xml 中的对应属性。
3. buildTypes 方法
buildTypes 方法定义了如何构建不同版本的 app。
4. dependencies
dependencies 定义了 APP 所有的依赖包。
一个依赖需要定义三个元素:group,name 和 version。
- group 意味着创建该 library 的组织名,通常这会是包名。
- name 是该 library 的唯一标示。
- version 是该 library 的版本号。
我们来看看如何申明依赖:
dependencies {
compile 'com.google.code.gson:gson:2.3'
compile 'com.squareup.retrofit:retrofit:1.9.0'
}
好了,现在你会用 Gradle 插件了吧!
**PS:更多精彩内容,请查看 --> 《Android 性能优化》
**PS:更多精彩内容,请查看 --> 《Android 性能优化》
**PS:更多精彩内容,请查看 --> 《Android 性能优化》