当前位置: 代码网 > it编程>App开发>Android > Android kotlin build.gradle.kts配置

Android kotlin build.gradle.kts配置

2024年07月28日 Android 我要评论
重新build了下代码,然后找编译后的代码,发现确实没有生成BuildConfig。之前代码相比,也就是AGP的版本升级了下,那猜测是不是跟AGP8.0.0的版本有关,于是在BuildType中手动添加了个buildConfigField,想以此方式强制生成下BuildConfig。我们在新建一个项目然后直接进行Build apk,可以生成一个app_debug.apk的apk文件,那么文件是怎么产生的呢?不同flavor的应用,加载不同的lib,然后某些代码文件,资源也可以使用对应文件夹下的内容替代。

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-: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"
                }
            }
        }
    }

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com