// 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 非常的人性化