android studio build.gradle 生成模板
时间: 2025-06-28 20:24:18 浏览: 19
### Android Studio 中 `build.gradle` 文件的标准模板
#### 根目录下的 `build.gradle`
根目录中的 `build.gradle` 主要负责配置整个项目的通用设置,包括依赖管理和插件声明。
```groovy
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.8.0' // Kotlin 版本号可以依据需求调整
repositories {
google()
mavenCentral() // 添加 Maven Central 仓库支持更多开源库
}
dependencies {
classpath "com.android.tools.build:gradle:7.4.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
```
此部分定义了 Gradle 构建脚本所需的类路径依赖以及全局可用的存储库列表[^1]。
#### 应用模块 (`app`) 下的 `build.gradle`
该文件位于应用程序模块内,主要用于指定具体的应用程序构建逻辑,如编译 SDK 版本、默认配置和其他必要的细节。
```groovy
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 33 // 编译使用的 API 级别
defaultConfig {
applicationId "com.example.myapplication" // 替换成实际包名
minSdkVersion 21 // 支持最低版本
targetSdkVersion 33 // 推荐的目标版本
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 "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
```
上述代码展示了如何通过 `defaultConfig` 设置基本参数,并利用 `dependencies` 块引入所需库。此外还包含了针对不同构建类型的特殊处理方式,比如发布版会启用混淆工具 ProGuard 来保护源码[^2]。
对于其他非应用模块(例如库),其结构相似但可能缺少某些特定于应用的部分,如 `applicationId` 和测试框架集成等[^4]。
阅读全文
相关推荐




















