当前位置:   article > 正文

Android kotlin build.gradle.kts配置

build.gradle.kts

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]部分用于声明插件
  注意:不要使用驼峰命名方式,单词使用 - 分割:

  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

    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)

  1. plugins {
  2. id("com.android.application")
  3. kotlin("android")
  4. kotlin("kapt")
  5. }
  6. android {
  7. compileSdkVersion(29)
  8. defaultConfig {
  9. applicationId = "com.xxx.xxxxx"
  10. minSdkVersion(21)
  11. targetSdkVersion(29)
  12. versionCode = 27
  13. versionName = "2.2.0"
  14. resConfigs("zh")
  15. ndk {
  16. abiFilters += listOf("armeabi-v7a","arm64-v8a")
  17. }
  18. }
  19. //开启dataBinding
  20. buildFeatures {
  21. dataBinding = true
  22. buildConfig=true
  23. }
  24. //图片已压缩 指定aapt不做图片压缩 因为可能会反而增加图片大小
  25. aaptOptions {
  26. // cruncherEnabled = false
  27. }
  28. //关闭lint检查
  29. lintOptions {
  30. disable("ResourceType")
  31. // abortOnError = false
  32. }
  33. //jniLibs目录指向libs目录
  34. sourceSets {
  35. getByName("main") {
  36. jniLibs.srcDirs("libs")
  37. }
  38. }
  39. //优化transformClassDexBuilderForDebug的时间
  40. dexOptions {
  41. preDexLibraries = true
  42. maxProcessCount = 8
  43. }
  44. //禁止生成依赖元数据 不上play用不到
  45. dependenciesInfo {
  46. includeInApk = false
  47. }
  48. //jdk1.8支持
  49. compileOptions {
  50. sourceCompatibility = JavaVersion.VERSION_1_8
  51. targetCompatibility = JavaVersion.VERSION_1_8
  52. }
  53. kotlinOptions {
  54. jvmTarget = JavaVersion.VERSION_1_8.toString()
  55. }
  56. //签名配置
  57. signingConfigs {
  58. getByName("debug") {
  59. storeFile = file("../xxx.jks")
  60. storePassword = "xxx"
  61. keyAlias = "xxx"
  62. keyPassword = "xxx"
  63. }
  64. }
  65. buildTypes {
  66. getByName("debug") {
  67. //签名
  68. signingConfig = signingConfigs.getByName("debug")
  69. //git提交次数 作为测试包版本后缀
  70. buildConfigField("int", "GIT_COMMIT_COUNT", getGitCommitCount())
  71. }
  72. register("alpha") {
  73. //继承debug配置
  74. initWith(getByName("debug"))
  75. //混淆
  76. isMinifyEnabled = true
  77. proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
  78. //ZipAlignEnabled优化
  79. isZipAlignEnabled = true
  80. //移除无用的resource文件
  81. isShrinkResources = true
  82. }
  83. getByName("release") {
  84. //继承alpha配置
  85. initWith(getByName("alpha"))
  86. //关闭debug
  87. debuggable(false)
  88. }
  89. }
  90. //release打包时自定义apk名字、输出路径
  91. android.applicationVariants.all {
  92. outputs.all {
  93. if (this is com.android.build.gradle.internal.api.ApkVariantOutputImpl) {
  94. this.outputFileName = "xxxx.apk"
  95. }
  96. }
  97. }
  98. }
  99. //获取git提交次数
  100. fun getGitCommitCount(): String {
  101. val os = org.apache.commons.io.output.ByteArrayOutputStream()
  102. project.exec {
  103. commandLine = "git rev-list --count HEAD".split(" ")
  104. standardOutput = os
  105. }
  106. return String(os.toByteArray()).trim()
  107. }
  108. //依赖库
  109. apply(from = "depends.gradle")

Kotlin中的Gradle_build.gradle.kts-CSDN博客


官方文档Gradle-kotlinGradle 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. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/159361
推荐阅读
相关标签
  

闽ICP备14008679号