1. 添加 maven 仓库
1. 1. settings配置
1. 1.1. settings.gradle
repositories { maven {url 'https://maven.aliyun.com/repository/public/'} mavenCentral() }
1. 1.2. settings.gradle.kts
repositories { maven { setUrl("https://maven.aliyun.com/repository/public/") } mavenCentral() }
1. 2. gradle配置
1. 2.1. build.gradle
implementation 'com.github.bumptech.glide:glide:4.12.0'
1. 2.2. build.gradle.kts
implementation(libs.glide)
版本号在gradle文件夹下 libs.versions.toml文件中添加
1. 2.2.1. build.gradle.kts
libs.versions.toml文件用来抽离依赖来加载,文件由 4 个主要部分组成:
(1)[versions]部分用于声明可以被依赖项引用的版本
(2)[libraries]部分用于声明坐标的别名
(3)[bundles]部分用于声明依赖包
(4)[plugins]部分用于声明插件
注意:不要使用驼峰命名方式,单词使用 - 分割:
[versions] groovy = "3.0.5" checkstyle = "8.37" [libraries] groovy-core = { module = "org.codehaus.groovy:groovy", version.ref = "groovy" } groovy-json = { module = "org.codehaus.groovy:groovy-json", version.ref = "groovy" } groovy-nio = { module = "org.codehaus.groovy:groovy-nio", version.ref = "groovy" } commons-lang3 = { group = "org.apache.commons", name = "commons-lang3", version = { strictly = "[3.8, 4.0[", prefer="3.9" } } [bundles] groovy = ["groovy-core", "groovy-json", "groovy-nio"] [plugins] versions = { id = "com.github.ben-manes.versions", version = "0.45.0" }
2. Android Studio 如何配置打包后的文件名称
我们在新建一个项目然后直接进行Build apk,可以生成一个app_debug.apk的apk文件,那么文件是怎么产生的呢?
2.1. build.gradle
//**********打包设置开始********** //自定义生成的apk的地址及名称 def apkName; signingConfigs { release { v1SigningEnabled true v2SigningEnabled true storeFile file('./keystore/insour_szyj.keystore') storePassword 'insour_szyj' keyAlias 'insour_szyj' keyPassword 'insour_szyj' } debug { v1SigningEnabled true v2SigningEnabled true storeFile file('./keystore/insour_szyj.keystore') storePassword 'insour_szyj' keyAlias 'insour_szyj' keyPassword 'insour_szyj' } } buildTypes { debug { // minifyEnabled false//混淆 minifyEnabled true shrinkResources true // 不显示Log buildConfigField "boolean", "LOG_DEBUG", "false" proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false apkName = "szyj.apk" signingConfig signingConfigs.release } release { // minifyEnabled false//混淆 minifyEnabled true shrinkResources true // 不显示Log buildConfigField "boolean", "LOG_DEBUG", "false" proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false apkName = "szyj.apk" signingConfig signingConfigs.release } } android.applicationVariants.all { variant -> variant.outputs.all { if (outputFileName.endsWith('.apk')) { //这里使用之前定义apk文件名称 outputFileName = apkName } } } // android.applicationVariants.all { // variant -> variant.outputs.all { output -> // def date = new Date().format("yyMMdd", // TimeZone.getTimeZone("GMT+08")) // if (variant.buildType.name == 'debug'){ // output.outputFileName = "项目名称_" + // "${android.defaultConfig.versionName}_${date}_debug.apk" // }else if (variant.buildType.name == 'release'){ // output.outputFileName = "项目名称_" + // "${android.defaultConfig.versionName}_${date}_release.apk" // } // } // } //**********打包设置结束**********
2.2. build.gradle.kts
//**********打包设置开始********** signingConfigs { // create("release") { // storeFile = file("./keystore/insour_szyj.keystore") // storePassword = "insour_szyj" // keyAlias = "insour_szyj" // keyPassword = "insour_szyj" // } getByName("debug") { enableV1Signing =true enableV2Signing =true enableV3Signing =true enableV4Signing =true storeFile = file("./keystore/insour_szyj.keystore") storePassword = "insour_szyj" keyAlias = "insour_szyj" keyPassword = "insour_szyj" } register("release") { enableV1Signing =true enableV2Signing =true enableV3Signing =true enableV4Signing =true storeFile = file("./keystore/insour_szyj.keystore") storePassword = "insour_szyj" keyAlias = "insour_szyj" keyPassword = "insour_szyj" } } buildTypes { debug { isMinifyEnabled = false isShrinkResources = false proguardFiles(getDefaultProguardFile( "proguard-android-optimize.txt"), "proguard-rules.pro") } release { isMinifyEnabled = false isShrinkResources = false proguardFiles(getDefaultProguardFile( "proguard-android-optimize.txt"), "proguard-rules.pro") } } // 输出类型 android.applicationVariants.all { // 编译类型 val buildType = this.buildType.name val date = SimpleDateFormat("yyyyMMddHHmmss").format(Date()) outputs.all { // 判断是否是输出 apk 类型 if (this is com.android.build.gradle .internal.api.ApkVariantOutputImpl) { this.outputFileName = "szyj" + "_${android.defaultConfig.versionName}_${date}_${buildType}.apk" } } } //**********打包设置结束**********
3. sourceSets配置
3.1. build.gradle
sourceSets { main { jniLibs.srcDirs = ['libs'] } }
3.2. build.gradle.kts
//jniLibs目录指向libs目录 sourceSets { getByName("main") { jniLibs.srcDirs("libs") } }
4. BuildConfig不生成
新建了一个demo,其依赖的AGP版本是8.0.0。但是在运行过程中报了一个错误就是找不到BuildConfig。
重新build了下代码,然后找编译后的代码,发现确实没有生成BuildConfig。清缓存,重启AS都没有用。之前代码相比,也就是AGP的版本升级了下,那猜测是不是跟AGP8.0.0的版本有关,于是在BuildType中手动添加了个buildConfigField,想以此方式强制生成下BuildConfig。
运行报错
Build Type 'debug' contains custom BuildConfig fields, but the feature is disabled.
提示BuildConfig 处于禁用状态…看来是新版本的AGP默认禁用了生成BuildConfig。BuildFeatures源码看到了一个配置buildConfig的注释如下。
果然如此,默认是禁用状态。在buildFeatures配置中把buildConfig值手动设为true,重新build下就好了
//开启dataBinding buildFeatures { dataBinding = true buildConfig=true }
5. Kotlin Build.gradle脚本编写(build.gradle.kts)
plugins { id("com.android.application") kotlin("android") kotlin("kapt") } android { compileSdkVersion(29) defaultConfig { applicationId = "com.xxx.xxxxx" minSdkVersion(21) targetSdkVersion(29) versionCode = 27 versionName = "2.2.0" resConfigs("zh") ndk { abiFilters += listOf("armeabi-v7a","arm64-v8a") } } //开启dataBinding buildFeatures { dataBinding = true buildConfig=true } //图片已压缩 指定aapt不做图片压缩 因为可能会反而增加图片大小 aaptOptions { // cruncherEnabled = false } //关闭lint检查 lintOptions { disable("ResourceType") // abortOnError = false } //jniLibs目录指向libs目录 sourceSets { getByName("main") { jniLibs.srcDirs("libs") } } //优化transformClassDexBuilderForDebug的时间 dexOptions { preDexLibraries = true maxProcessCount = 8 } //禁止生成依赖元数据 不上play用不到 dependenciesInfo { includeInApk = false } //jdk1.8支持 compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = JavaVersion.VERSION_1_8.toString() } //签名配置 signingConfigs { getByName("debug") { storeFile = file("../xxx.jks") storePassword = "xxx" keyAlias = "xxx" keyPassword = "xxx" } } buildTypes { getByName("debug") { //签名 signingConfig = signingConfigs.getByName("debug") //git提交次数 作为测试包版本后缀 buildConfigField("int", "GIT_COMMIT_COUNT", getGitCommitCount()) } register("alpha") { //继承debug配置 initWith(getByName("debug")) //混淆 isMinifyEnabled = true proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") //ZipAlignEnabled优化 isZipAlignEnabled = true //移除无用的resource文件 isShrinkResources = true } getByName("release") { //继承alpha配置 initWith(getByName("alpha")) //关闭debug debuggable(false) } } //release打包时自定义apk名字、输出路径 android.applicationVariants.all { outputs.all { if (this is com.android.build.gradle.internal.api.ApkVariantOutputImpl) { this.outputFileName = "xxxx.apk" } } } } //获取git提交次数 fun getGitCommitCount(): String { val os = org.apache.commons.io.output.ByteArrayOutputStream() project.exec { commandLine = "git rev-list --count HEAD".split(" ") standardOutput = os } return String(os.toByteArray()).trim() } //依赖库 apply(from = "depends.gradle")
Kotlin中的Gradle_build.gradle.kts-CSDN博客
官方文档Gradle-kotlin:Gradle Kotlin DSL Primer
全局配置文件:settings.gradle.kts
pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "Test" include(":app") include(":mylibrary")
全局配置文件build.gradle.kts
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { maven(uri("https://maven.aliyun.com/repository/public/")) google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:7.0.4") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { maven(uri("https://maven.aliyun.com/repository/public/")) google() mavenCentral() } } //clean Task tasks { val clean by registering(Delete::class) { delete(buildDir) } } //clean Task也可以这样写 tasks.register<Delete>("clean") { delete(rootProject.buildDir) }
项目app配置文件build.gradle.kts
plugins { id("com.android.application") id("org.jetbrains.kotlin.android") } android { namespace = "com.baidu.main" compileSdk = 33 defaultConfig { applicationId = "com.baidu.main" minSdk = 24 targetSdk = 33 versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary = true } } buildTypes { release { isMinifyEnabled = 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" } buildFeatures { compose = true } composeOptions { kotlinCompilerExtensionVersion = "1.4.3" } packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}" } } } dependencies { implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1") implementation("androidx.activity:activity-compose:1.7.0") implementation(platform("androidx.compose:compose-bom:2023.03.00")) implementation("androidx.compose.ui:ui") implementation("androidx.compose.ui:ui-graphics") implementation("androidx.compose.ui:ui-tooling-preview") implementation("androidx.compose.material3:material3") implementation(project(mapOf("path" to ":mylibrary"))) testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00")) androidTestImplementation("androidx.compose.ui:ui-test-junit4") debugImplementation("androidx.compose.ui:ui-tooling") debugImplementation("androidx.compose.ui:ui-test-manifest") }
配置flavor
flavorDimensions.add("platform") productFlavors { create("zim200") { dimension = "platform" } create("ysm8") { dimension = "platform" } }
根据 buildtypes配置签名
buildTypes { debug { isDebuggable = true isMinifyEnabled = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) signingConfig = null productFlavors.getByName("ysm8") { signingConfig = signingConfigs.getByName("ysm8") } productFlavors.getByName("zim200") { signingConfig = signingConfigs.getByName("zim200") } } release { initWith(buildTypes.getByName("debug")) isMinifyEnabled = true isDebuggable = false proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } }
配置lib文件夹
dependencies { add( "zim200Implementation", fileTree(mapOf("dir" to "libszim", "include" to listOf("*.jar", "*.aar"))) ) add( "ysm8Implementation", fileTree(mapOf("dir" to "libsysm8", "include" to listOf("*.jar", "*.aar"))) ) implementation(project(":TtsTool")) testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit-ktx:1.1.3") androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0") }
对应的lib文件夹目录结构
不同flavor的应用,加载不同的lib,然后某些代码文件,资源也可以使用对应文件夹下的内容替代
配置密钥
signingConfigs { create("zim200") { storeFile = file("../signature/platform.keystore") storePassword = "xxx" keyAlias = "xxx" keyPassword = "xxx" } create("ysm8") { storeFile = file("../signature/ysm8.jks") storePassword = "xxx" keyAlias = "xxx" keyPassword = "xxx" // v1SigningEnabled = true // v1SigningEnabled = true isV1SigningEnabled = true } }
关于abi拆分和apk命名
//按abi拆分包 splits { abi { isEnable = true reset() include("armeabi-v7a", "arm64-v8a")//支持的ABIs isUniversalApk = true //要不要一个全量ABIs的包 } } val abiCodes = mapOf("armeabi-v7a" to 1, "arm64-v8a" to 2, "x86" to 3, "x86_64" to 4) android.applicationVariants.all { val buildType = this.buildType.name val flavorName = this.flavorName val variant = this outputs.all { val name = this.filters.find { it.filterType == com.android.build.api.variant.FilterConfiguration.FilterType.ABI.name }?.identifier val baseAbiCode = abiCodes[name] if (baseAbiCode != null) { //写入cpu架构信息 variant.buildConfigField("String", "CUP_ABI", "\"${name}\"") } if (this is com.android.build.gradle.internal.api.ApkVariantOutputImpl) { //修改apk名称 if (buildType == "release") { this.outputFileName = "apkname_${flavorName}_${name}_${buildType}_v${variant.versionName}.apk" } else if (buildType == "debug") { this.outputFileName = "apkname_${flavorName}_${name}_${buildType}_v${variant.versionName}.apk" } } } }