如何在 Android 中自动化应用版本控制

How to automate app versioning in Android

我有一个 CI 工具 (Bamboo),它运行我的单元测试并构建应用程序-release.apk。每当我对我的应用程序进行更改并成功构建时,我都会创建一个新版本 number.I 将版本号和构建时间存储在一个文件中。我可以让 Gradle 从该文件中读取并相应地更改应用程序版本吗?

我的文件内容如下所示:

ProductVersion=0.0.0.0.0
ProductBuildDateTime=2017-01-01T00:00:00.000

当然可以,我就是这样做的:

我将我的版本存储在 version.properties 文件中。

然后在应用程序的 build.gradle 我使用以下代码:

//Path to the file of your properties file that contains the version number
final String VERSION_PROPERTIES_FILE = projectDir.getParentFile().getParent() + "/file.properties"

 /**
 * Returns the id of the property name from config file, null if it doesn't exist
     * @param propertyName
     * @param properties file name in assets dir
     * @return
     */
    def getPropertyFromFile(propertiesFilePath, propertyName) {
        def propsFile = new File(propertiesFilePath);
        if (propsFile.canRead()) {
            def props = new Properties();
            props.load(new FileInputStream(propsFile));
            return props.getProperty(propertyName, null);
        } else {
            throw new GradleException("Could not read $propertiesFilePath !")
        }
    }

int vCode = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionCode") as Integer
String vName = getPropertyFromFile(VERSION_PROPERTIES_FILE, "versionName")

defaultConfig {
    applicationId "com.x.x"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode vCode
    versionName vName
}

在您的情况下,您可以将 "ProductBuildDateTime""ProductVersion" 传递给读取文件的方法。

如果你的意思是如何去做,那么只需做类似
的事情
....def properties = new Properties()
....def 文件 = 新文件('version.properties')
....file.withInputStream {
.......properties.load它
....}
....properties.ProductVersion = ...
....properties.ProductBuildDateTime = ...
....file.withOuputStream {
.......properties.store 对,没错
....}

如果您想从文件中读取构建信息,您可以使用给定答案的更简化版本,如下所示:

def getCIProperty(String key)
{
    Properties properties = new Properties()
    properties.load( file("Bamboo File Absolute Path").readLines().join("\n"))
    properties.getProperty(key)
}

getCIProperty('ProductVersion')
getCIProperty('ProductBuildDateTime')

只需将其复制并粘贴到您的主构建文件中,而不是 settings.gradle 文件

或者如果您使用的是 bamboo ,您可以通过让 bamboo 像这样在构建命令中传递这些属性来更轻松地做到这一点:

将这些代码复制并粘贴到构建脚本中的任何位置(即使在 settings.gradle 中)

gradle.productVersion = getProperty('ProductVersion')
gradle.productBuildDateTime = getProperty('ProductBuildDateTime')

现在只需让 bamboo 将这两个参数添加到构建命令中,如下所示:

gradle -PProductVersion=0.0.0.0.0   -PProductBuildDateTime=2017-01-01T00:00:00.000   clean   assembleRelease

提示:clean 和 assembleRelease 是构建脚本中的任务,您可以调用任何您想要的任务。