build.gradle
文件是一个核心的构建脚本文件,在 Android 应用的项目中起着非常重要的作用。它基于 Groovy 语言并使用 Gradle 构建工具,用于定义构建配置,如 Android SDK 版本,依赖库等等。
在一个标准的 Android 项目中,通常会有两个 build.gradle
文件:
- 项目级别的
build.gradle
(Project: My Application): 这个文件主要定义了所有子模块都需要使用的构建配置,例如 Gradle 插件版本等。 - 模块级别的
build.gradle
(Module: app): 这个文件定义了模块(一个应用或者库)的特定构建配置,例如应用的 id,版本号,版本名,最小 SDK,目标 SDK,以及各种依赖项等等。
下面是一个典型的模块级别 build.gradle
文件的示例:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
apply plugin: 'com.android.application' // 应用 android 应用程序插件
apply plugin: 'kotlin-android' // 应用 kotlin-android 插件(如果你的项目使用 Kotlin)
android {
compileSdkVersion 30 // 编译 SDK 版本
defaultConfig {
applicationId "com.example.myapp" // 应用 ID
minSdkVersion 16 // 最小支持的 SDK 版本
targetSdkVersion 30 // 目标 SDK 版本
versionCode 1 // 版本号
versionName "1.0" // 版本名称
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false // 在发布版中是否启用代码混淆
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8 // 设置源代码兼容性
targetCompatibility JavaVersion.VERSION_1_8 // 设置目标代码兼容性
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) // 导入本地 jar 包
implementation 'androidx.appcompat:appcompat:1.2.0' // 导入 appcompat 库
implementation 'com.google.android.material:material:1.2.1' // 导入 material 设计库
implementation 'androidx.constraintlayout:constraintlayout:2.0.4' // 导入 constraintlayout 布局库
testImplementation 'junit:junit:4.+' // 导入 junit 测试库
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
以上就是一个简单的 build.gradle
文件示例,包括了基本的配置选项以及注释解释。
网友评论