Android Studio greadle打包拷贝apk

2023-02-20  本文已影响0人  Zachary46

根目录build.gradle下添加如下代码:

subprojects() {
    //新版gradle每次打包会清空release文件夹,拷贝一份到其它地方保存包~
    //assembleRelease这个任务,就是我们普通的打包任务。打release包。
    def releaseTasks = project.getTasksByName("assembleRelease", false)
    copyApkFile(releaseTasks, project)
}

def copyApkFile(Set<Task> tasks, Project project) {
    def fromDir = "/build/outputs/apk/release"
    for (task in tasks) {
        def dir = project.getProjectDir().getAbsolutePath()
        println "assemble release dir = $dir"
        //我们目前存放打包后apk的目录
        def apkDir = dir + fromDir
        def file = new File(apkDir)

        if (file.exists()) {
            def isDelete = delete(apkDir)
            println "del: $isDelete"
        }
        //在task执行完成之后
        task.doLast {
            if (file.exists()) {
                //将生成的apk整个目录复制到我们指定位置
                copy {
                    println "copy dir = ${file.getAbsolutePath()}"
                    from apkDir
                    def toDir = rootProject.getRootDir().getAbsolutePath() + "/apk/"
                    println "to dir = ${toDir}"
                    into toDir
                }
            }
        }
    }
}

用assembleRelease命令打包(前提是配置了signingConfigs)


image.png

在app目录下的build.gradle配置signingConfigs

signingConfigs {
        debug {
            storeFile file(xxx)
            storePassword xxx
            keyAlias = xxx
            keyPassword xxx
        }
        release {
            storeFile file(xxx)
            storePassword xxx
            keyAlias = xxx
            keyPassword xxx
        }
    }

输出包名最后改一下,方便存储

def appEnv = "pro"

def releaseTime() {
    return new Date().format("yyyyMMddHHmm", TimeZone.getTimeZone("GMT+08:00"))
}

android.applicationVariants.all {
        variant ->
            variant.outputs.all {
                //在这里修改apk文件名
                outputFileName = "${appEnv}_${variant.versionName}_${releaseTime()}.apk"
            }
 }

上一篇下一篇

猜你喜欢

热点阅读