AndroidStudio3.2版本自定义apk名称编译异常问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rrr9805/article/details/82976972
项目从3.x版本升级到3.2版本时原有的自定义输出apk名称的代码已经失效新的写法更改为
//这段脚本是写在项目级别的gradle文件中的
//  AS3.2版本//输出apk自定义名称
android {
        applicationVariants.all { variant ->
            variant.outputs.each { output ->
                output.versionCodeOverride = rootProject.gitVersionCode()
                output.versionNameOverride = rootProject.gitVersionTag()
                if (variant.name.endsWith("Debug")) {
                    //debug包使用git自动的版本号
                    output.outputFileName = "$applicationId _v${variant.mergedFlavor.versionName}_${debugTime()}_debug.apk"
                } else {
                    //release包使用git自动的版本号和版本名称
                    output.outputFileName = "$applicationId _v${variant.mergedFlavor.versionName}_code${variant.mergedFlavor.versionCode}_${releaseTime()}_release.apk"
                }
            }
        }
    }
  1. 其中的rootProject.gitVersionCode()和rootProject.gitVersionTag()方法,是为了结合git自动的生成版本号和版本名称.而它是在项目级别的gradle文件中申明的(最外层声明)相关代码如下
def gitVersionCode() {
//    def cmd = 'git rev-list --all-match --first-parent --count'
    def cmd = 'git rev-list HEAD --count'
    cmd.execute().text.trim().toInteger()
}

def gitVersionTag() {
    def cmd = 'git describe --tags'
    def version = cmd.execute().text.trim()

    def pattern = "-(\\d+)-g"
    def matcher = version =~ pattern

    if (matcher) {
        version = version.substring(0, matcher.start()) + "." + matcher[0][1]
    } else {
//        version = version + ".0"
    }
    return version
}

此处仅为代码片段,具体如何结合git自动生成版本号和版本名称,请自行查阅(此处有坑,不同版本的AndroidStudio配置方法不同)

2.debugTime()方法和releaseTime()方法是在脚本的顶部声明的方法如下

static def releaseTime() {
    return new Date().format("yyyy-MM-dd-HH-mm", TimeZone.getDefault())//包含时分秒
}

static def debugTime() {
//    return new Date().format("yyyy-MM-dd", TimeZone.getDefault())
    return new Date().format("yyyy", TimeZone.getDefault())
}

原有的自定义apk名称写法为,具体示意见上述3.2版本
    //AS3.x版本//输出apk自定义名称
    android.applicationVariants.all { variant ->
        variant.outputs.all {
            variant.mergedFlavor.versionCode = rootProject.gitVersionCode()
            variant.mergedFlavor.versionName = rootProject.gitVersionTag()
            if (variant.name.endsWith("Debug")) {
                //debug包使用git自动的版本号
                outputFileName = "$applicationId _v${variant.mergedFlavor.versionName}_${debugTime()}_debug.apk"
            } else {
                //release包使用git自动的版本号和版本名称
                outputFileName = "$applicationId _v${variant.mergedFlavor.versionName}_code${variant.mergedFlavor.versionCode}_${releaseTime()}_release.apk"
            }
        }
    }
3.x之前版本写法也是不同的,这里不做赘述

猜你喜欢

转载自blog.csdn.net/rrr9805/article/details/82976972