Android kotlin build.gradle.kts配置

打印 上一主题 下一主题

主题 512|帖子 512|积分 1538

1. 添加 maven 仓库

1. 1. settings配置

1. 1.1. settings.gradle

  1. repositories {
  2.     maven {url 'https://maven.aliyun.com/repository/public/'}
  3.     mavenCentral()
  4. }
复制代码
1. 1.2. settings.gradle.kts

  1. repositories {
  2.     maven {
  3.         setUrl("https://maven.aliyun.com/repository/public/")
  4.     }
  5.     mavenCentral()
  6. }
复制代码
1. 2. gradle配置

1. 2.1. build.gradle

  1.   implementation 'com.github.bumptech.glide:glide:4.12.0'
复制代码
1. 2.2. build.gradle.kts

  1.     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]部分用于声明插件
  注意:不要使用驼峰定名方式,单词使用 - 分割:
  1. [versions]
  2. groovy = "3.0.5"
  3. checkstyle = "8.37"
  4. [libraries]
  5. groovy-core = { module = "org.codehaus.groovy:groovy", version.ref = "groovy" }
  6. groovy-json = { module = "org.codehaus.groovy:groovy-json", version.ref = "groovy" }
  7. groovy-nio = { module = "org.codehaus.groovy:groovy-nio", version.ref = "groovy" }
  8. commons-lang3 = { group = "org.apache.commons", name = "commons-lang3", version = { strictly = "[3.8, 4.0[", prefer="3.9" } }
  9. [bundles]
  10. groovy = ["groovy-core", "groovy-json", "groovy-nio"]
  11. [plugins]
  12. versions = { id = "com.github.ben-manes.versions", version = "0.45.0" }
复制代码
2. Android Studio 如何配置打包后的文件名称

  我们在新建一个项目然后直接进行Build apk,可以生成一个app_debug.apk的apk文件,那么文件是怎么产生的呢?

2.1. build.gradle

  1.     //**********打包设置开始**********
  2.     //自定义生成的apk的地址及名称
  3.     def apkName;
  4.     signingConfigs {
  5.         release {
  6.             v1SigningEnabled true
  7.             v2SigningEnabled true
  8.             storeFile file('./keystore/insour_szyj.keystore')
  9.             storePassword 'insour_szyj'
  10.             keyAlias 'insour_szyj'
  11.             keyPassword 'insour_szyj'
  12.         }
  13.         debug {
  14.             v1SigningEnabled true
  15.             v2SigningEnabled true
  16.             storeFile file('./keystore/insour_szyj.keystore')
  17.             storePassword 'insour_szyj'
  18.             keyAlias 'insour_szyj'
  19.             keyPassword 'insour_szyj'
  20.         }
  21.     }
  22.     buildTypes {
  23.         debug {
  24. //            minifyEnabled false//混淆
  25.             minifyEnabled true
  26.             shrinkResources true
  27.             // 不显示Log
  28.             buildConfigField "boolean", "LOG_DEBUG", "false"
  29.             proguardFiles getDefaultProguardFile('proguard-android.txt'),
  30.                     'proguard-rules.pro'
  31.             aaptOptions.cruncherEnabled = false
  32.             aaptOptions.useNewCruncher = false
  33.             apkName = "szyj.apk"
  34.             signingConfig signingConfigs.release
  35.         }
  36.         release {
  37. //            minifyEnabled false//混淆
  38.             minifyEnabled true
  39.             shrinkResources true
  40.             // 不显示Log
  41.             buildConfigField "boolean", "LOG_DEBUG", "false"
  42.             proguardFiles getDefaultProguardFile('proguard-android.txt'),
  43.                     'proguard-rules.pro'
  44.             aaptOptions.cruncherEnabled = false
  45.             aaptOptions.useNewCruncher = false
  46.             apkName = "szyj.apk"
  47.             signingConfig signingConfigs.release
  48.         }
  49.     }
  50.     android.applicationVariants.all { variant ->
  51.         variant.outputs.all {
  52.             if (outputFileName.endsWith('.apk')) {
  53.                 //这里使用之前定义apk文件名称
  54.                 outputFileName = apkName
  55.             }
  56.         }
  57.     }
  58. //    android.applicationVariants.all {
  59. //        variant -> variant.outputs.all { output ->
  60. //                def date = new Date().format("yyMMdd",
  61. //                        TimeZone.getTimeZone("GMT+08"))
  62. //                if (variant.buildType.name == 'debug'){
  63. //                    output.outputFileName = "项目名称_" +
  64. //                            "${android.defaultConfig.versionName}_${date}_debug.apk"
  65. //                }else if (variant.buildType.name == 'release'){
  66. //                    output.outputFileName = "项目名称_" +
  67. //                            "${android.defaultConfig.versionName}_${date}_release.apk"
  68. //                }
  69. //            }
  70. //    }
  71.     //**********打包设置结束**********
复制代码
2.2. build.gradle.kts

  1.   //**********打包设置开始**********
  2.     signingConfigs {
  3. //        create("release") {
  4. //            storeFile = file("./keystore/insour_szyj.keystore")
  5. //            storePassword = "insour_szyj"
  6. //            keyAlias = "insour_szyj"
  7. //            keyPassword = "insour_szyj"
  8. //        }
  9.         getByName("debug") {
  10.             enableV1Signing =true
  11.             enableV2Signing =true
  12.             enableV3Signing =true
  13.             enableV4Signing =true
  14.             storeFile = file("./keystore/insour_szyj.keystore")
  15.             storePassword = "insour_szyj"
  16.             keyAlias = "insour_szyj"
  17.             keyPassword = "insour_szyj"
  18.         }
  19.         register("release") {
  20.             enableV1Signing =true
  21.             enableV2Signing =true
  22.             enableV3Signing =true
  23.             enableV4Signing =true
  24.             storeFile = file("./keystore/insour_szyj.keystore")
  25.             storePassword = "insour_szyj"
  26.             keyAlias = "insour_szyj"
  27.             keyPassword = "insour_szyj"
  28.         }
  29.     }
  30.     buildTypes {
  31.         debug {
  32.             isMinifyEnabled = false
  33.             isShrinkResources = false
  34.             proguardFiles(getDefaultProguardFile(
  35.                     "proguard-android-optimize.txt"),
  36.                     "proguard-rules.pro")
  37.         }
  38.         release {
  39.             isMinifyEnabled = false
  40.             isShrinkResources = false
  41.             proguardFiles(getDefaultProguardFile(
  42.                     "proguard-android-optimize.txt"),
  43.                     "proguard-rules.pro")
  44.         }
  45.     }
  46.     // 输出类型
  47.     android.applicationVariants.all {
  48.         // 编译类型
  49.         val buildType = this.buildType.name
  50.         val date = SimpleDateFormat("yyyyMMddHHmmss").format(Date())
  51.         outputs.all {
  52.             // 判断是否是输出 apk 类型
  53.             if (this is com.android.build.gradle
  54.                     .internal.api.ApkVariantOutputImpl) {
  55.                 this.outputFileName = "szyj" +
  56.                         "_${android.defaultConfig.versionName}_${date}_${buildType}.apk"
  57.             }
  58.         }
  59.     }
  60.     //**********打包设置结束**********
复制代码
3. sourceSets配置

3.1. build.gradle

  1.     sourceSets {
  2.         main {
  3.             jniLibs.srcDirs = ['libs']
  4.         }
  5.     }
复制代码
3.2. build.gradle.kts

  1. //jniLibs目录指向libs目录
  2.     sourceSets {
  3.         getByName("main") {
  4.             jniLibs.srcDirs("libs")
  5.         }
  6.     }
复制代码
4. BuildConfig不生成

  新建了一个demo,其依赖的AGP版本是8.0.0。但是在运行过程中报了一个错误就是找不到BuildConfig。
重新build了下代码,然后找编译后的代码,发现确实没有生成BuildConfig。清缓存,重启AS都没有效。之前代码相比,也就是AGP的版本升级了下,那猜测是不是跟AGP8.0.0的版本有关,于是在BuildType中手动添加了个buildConfigField,想以此方式强制生成下BuildConfig。

  运行报错
  1. Build Type 'debug' contains custom BuildConfig fields, but the feature is disabled.
复制代码

  提示BuildConfig 处于禁用状态…看来是新版本的AGP默认禁用了生成BuildConfig。BuildFeatures源码看到了一个配置buildConfig的注释如下。

  果然如此,默认是禁用状态。在buildFeatures配置中把buildConfig值手动设为true,重新build下就好了
  1.     //开启dataBinding
  2.     buildFeatures {
  3.         dataBinding = true
  4.         buildConfig=true
  5.     }
复制代码

5. Kotlin Build.gradle脚本编写(build.gradle.kts)

  1. 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
  2.     buildFeatures {
  3.         dataBinding = true
  4.         buildConfig=true
  5.     }
  6.     //图片已压缩 指定aapt不做图片压缩 由于可能会反而增长图片巨细    aaptOptions {//        cruncherEnabled = false    }    //关闭lint检查    lintOptions {        disable("ResourceType")//        abortOnError  = false    }    //jniLibs目录指向libs目录
  7.     sourceSets {
  8.         getByName("main") {
  9.             jniLibs.srcDirs("libs")
  10.         }
  11.     }
  12.     //优化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
  1. pluginManagement {
  2.     repositories {
  3.         google()
  4.         mavenCentral()
  5.         gradlePluginPortal()
  6.     }
  7. }
  8. dependencyResolutionManagement {
  9.     repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
  10.     repositories {
  11.         google()
  12.         mavenCentral()
  13.     }
  14. }
  15. rootProject.name = "Test"
  16. include(":app")
  17. include(":mylibrary")
复制代码
 全局配置文件build.gradle.kts
  1. // Top-level build file where you can add configuration options common to all sub-projects/modules.
  2. buildscript {
  3.     repositories {
  4.         maven(uri("https://maven.aliyun.com/repository/public/"))
  5.         google()
  6.         mavenCentral()
  7.     }
  8.     dependencies {
  9.         classpath("com.android.tools.build:gradle:7.0.4")
  10.         classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10")
  11.         // NOTE: Do not place your application dependencies here; they belong
  12.         // in the individual module build.gradle files
  13.     }
  14. }
  15. allprojects {
  16.     repositories {
  17.         maven(uri("https://maven.aliyun.com/repository/public/"))
  18.         google()
  19.         mavenCentral()
  20.     }
  21. }
  22. //clean Task
  23. tasks {
  24.     val clean by registering(Delete::class) {
  25.         delete(buildDir)
  26.     }
  27. }
  28. //clean Task也可以这样写
  29. tasks.register<Delete>("clean") {
  30.     delete(rootProject.buildDir)
  31. }
复制代码
项目app配置文件build.gradle.kts
  1. plugins {
  2.     id("com.android.application")
  3.     id("org.jetbrains.kotlin.android")
  4. }
  5. android {
  6.     namespace = "com.baidu.main"
  7.     compileSdk = 33
  8.     defaultConfig {
  9.         applicationId = "com.baidu.main"
  10.         minSdk = 24
  11.         targetSdk = 33
  12.         versionCode = 1
  13.         versionName = "1.0"
  14.         testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
  15.         vectorDrawables {
  16.             useSupportLibrary = true
  17.         }
  18.     }
  19.     buildTypes {
  20.         release {
  21.             isMinifyEnabled = false
  22.             proguardFiles(
  23.                 getDefaultProguardFile("proguard-android-optimize.txt"),
  24.                 "proguard-rules.pro"
  25.             )
  26.         }
  27.     }
  28.     compileOptions {
  29.         sourceCompatibility = JavaVersion.VERSION_1_8
  30.         targetCompatibility = JavaVersion.VERSION_1_8
  31.     }
  32.     kotlinOptions {
  33.         jvmTarget = "1.8"
  34.     }
  35.     buildFeatures {
  36.         compose = true
  37.     }
  38.     composeOptions {
  39.         kotlinCompilerExtensionVersion = "1.4.3"
  40.     }
  41.     packaging {
  42.         resources {
  43.             excludes += "/META-INF/{AL2.0,LGPL2.1}"
  44.         }
  45.     }
  46. }
  47. dependencies {
  48.     implementation("androidx.core:core-ktx:1.9.0")
  49.     implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")
  50.     implementation("androidx.activity:activity-compose:1.7.0")
  51.     implementation(platform("androidx.compose:compose-bom:2023.03.00"))
  52.     implementation("androidx.compose.ui:ui")
  53.     implementation("androidx.compose.ui:ui-graphics")
  54.     implementation("androidx.compose.ui:ui-tooling-preview")
  55.     implementation("androidx.compose.material3:material3")
  56.     implementation(project(mapOf("path" to ":mylibrary")))
  57.     testImplementation("junit:junit:4.13.2")
  58.     androidTestImplementation("androidx.test.ext:junit:1.1.5")
  59.     androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
  60.     androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))
  61.     androidTestImplementation("androidx.compose.ui:ui-test-junit4")
  62.     debugImplementation("androidx.compose.ui:ui-tooling")
  63.     debugImplementation("androidx.compose.ui:ui-test-manifest")
  64. }
复制代码
配置flavor

  1.     flavorDimensions.add("platform")
  2.     productFlavors {
  3.         create("zim200") {
  4.             dimension = "platform"
  5.         }
  6.         create("ysm8") {
  7.             dimension = "platform"
  8.         }
  9.     }
复制代码
根据 buildtypes配置署名

  1. buildTypes {
  2.         debug {
  3.             isDebuggable = true
  4.             isMinifyEnabled = false
  5.             proguardFiles(
  6.                 getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
  7.             )
  8.             signingConfig = null
  9.             productFlavors.getByName("ysm8") {
  10.                 signingConfig = signingConfigs.getByName("ysm8")
  11.             }
  12.             productFlavors.getByName("zim200") {
  13.                 signingConfig = signingConfigs.getByName("zim200")
  14.             }
  15.         }
  16.         release {
  17.             initWith(buildTypes.getByName("debug"))
  18.             isMinifyEnabled = true
  19.             isDebuggable = false
  20.             proguardFiles(
  21.                 getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
  22.             )
  23.         }
  24.     }
复制代码
配置lib文件夹
  1. dependencies {
  2.     add(
  3.         "zim200Implementation",
  4.         fileTree(mapOf("dir" to "libszim", "include" to listOf("*.jar", "*.aar")))
  5.     )
  6.     add(
  7.         "ysm8Implementation",
  8.         fileTree(mapOf("dir" to "libsysm8", "include" to listOf("*.jar", "*.aar")))
  9.     )
  10.     implementation(project(":TtsTool"))
  11.     testImplementation("junit:junit:4.13.2")
  12.     androidTestImplementation("androidx.test.ext:junit-ktx:1.1.3")
  13.     androidTestImplementation("androidx.test.espresso:espresso-core:3.4.0")
  14. }
复制代码
对应的lib文件夹目录结构


不同flavor的应用,加载不同的lib,然后某些代码文件,资源也可以使用对应文件夹下的内容更换
配置密钥

  1. signingConfigs {
  2.         create("zim200") {
  3.             storeFile = file("../signature/platform.keystore")
  4.             storePassword = "xxx"
  5.             keyAlias = "xxx"
  6.             keyPassword = "xxx"
  7.         }
  8.         create("ysm8") {
  9.             storeFile = file("../signature/ysm8.jks")
  10.             storePassword = "xxx"
  11.             keyAlias = "xxx"
  12.             keyPassword = "xxx"
  13. //            v1SigningEnabled = true
  14. //            v1SigningEnabled = true
  15.             isV1SigningEnabled = true
  16.         }
  17.     }
复制代码
关于abi拆分和apk定名

  1. //按abi拆分包
  2.     splits {
  3.         abi {
  4.             isEnable = true
  5.             reset()
  6.             include("armeabi-v7a", "arm64-v8a")//支持的ABIs
  7.             isUniversalApk = true //要不要一个全量ABIs的包
  8.         }
  9.     }
  10.     val abiCodes = mapOf("armeabi-v7a" to 1, "arm64-v8a" to 2, "x86" to 3, "x86_64" to 4)
  11.     android.applicationVariants.all {
  12.         val buildType = this.buildType.name
  13.         val flavorName = this.flavorName
  14.         val variant = this
  15.         outputs.all {
  16.             val name =
  17.                 this.filters.find { it.filterType == com.android.build.api.variant.FilterConfiguration.FilterType.ABI.name }?.identifier
  18.             val baseAbiCode = abiCodes[name]
  19.             if (baseAbiCode != null) {
  20.                 //写入cpu架构信息
  21.                 variant.buildConfigField("String", "CUP_ABI", ""${name}"")
  22.             }
  23.             if (this is com.android.build.gradle.internal.api.ApkVariantOutputImpl) {
  24.                 //修改apk名称
  25.                 if (buildType == "release") {
  26.                     this.outputFileName =
  27.                         "apkname_${flavorName}_${name}_${buildType}_v${variant.versionName}.apk"
  28.                 } else if (buildType == "debug") {
  29.                     this.outputFileName =
  30.                         "apkname_${flavorName}_${name}_${buildType}_v${variant.versionName}.apk"
  31.                 }
  32.             }
  33.         }
  34.     }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

拉不拉稀肚拉稀

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表