Android 自动设置版本号与版本名称
Posted 安果移不动
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android 自动设置版本号与版本名称相关的知识,希望对你有一定的参考价值。
// version -------------------------------------------------
updateVersion()
def updateVersion() {
def propertiesFile = file("build.properties")
Properties properties = readProperties(propertiesFile)
def versionMajor = properties["version_major"].toString().toInteger()
def versionMinor = properties["version_minor"].toString().toInteger()
def versionPatch = properties["version_patch"].toString().toInteger()
def versionBuild = properties["version_build"].toString().toInteger()
def versionStore = properties["version_store"].toString().toInteger()
if (isReleaseTask()) {
System.out.println(">>> Building Release...")
versionPatch++
versionStore++
versionBuild = 0
properties["version_patch"] = versionPatch.toString()
properties["version_store"] = versionStore.toString()
properties["version_build"] = versionBuild.toString()
writeProperties(propertiesFile, properties)
}
if (isTestTask()) {
System.out.println(">>> Running Tests...")
versionBuild++
properties["version_build"] = versionBuild.toString()
writeProperties(propertiesFile, properties)
}
def versionName = "${versionMajor}.${versionMinor}.${versionPatch}"
def applicationId = android.defaultConfig.applicationId
if (!isReleaseTask()) {
versionName = versionName + ".${versionBuild}"
applicationId = applicationId + android.buildTypes.debug.applicationIdSuffix
}
System.out.println(">>> " + project.parent.name + " " + versionName + " (" + versionStore + ") " + applicationId)
android.defaultConfig.versionCode = versionStore
android.defaultConfig.versionName = versionName
}
def isTestTask() {
def tasks = gradle.getStartParameter().getTaskNames()
return ":app:testDebugUnitTest" in tasks || "testDebugUnitTest" in tasks ||
":app:testReleaseUnitTest" in tasks || "testReleaseUnitTest" in tasks
}
def isReleaseTask() {
def tasks = gradle.getStartParameter().getTaskNames()
return ":app:assembleRelease" in tasks || "assembleRelease" in tasks ||
":app:bundleRelease" in tasks || "bundleRelease" in tasks
}
static Properties readProperties(propertiesFile) {
if (propertiesFile.canRead()) {
Properties properties = new Properties()
def inputStream = new FileInputStream(propertiesFile)
properties.load(inputStream)
inputStream.close()
return properties
} else {
def message = ">>> Could not read " + propertiesFile.name + " file!"
System.err.println(message)
throw new GradleException(message)
}
}
def static writeProperties(propertiesFile, properties) {
def writer = propertiesFile.newWriter()
properties.store(writer, "Build Properties")
writer.close()
}
根目录新建文件 build.properties内容如下
#Build Properties
#Sat Aug 07 14:32:46 EDT 2021
version_store=1
version_major=1
version_patch=0
version_minor=0
version_build=0
在每次编译正式版本后版本就会加1 非常的人性化
以上是关于Android 自动设置版本号与版本名称的主要内容,如果未能解决你的问题,请参考以下文章
Android SDK版本号与API Level 的对应关系-转
Android Studio 打包apk,自动追加版本号和版本名称