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

时间:2017-12-05 13:10:11

标签: android gradle versioning

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

我的文件内容如下:

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

3 个答案:

答案 0 :(得分:2)

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

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

然后在app的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"传递给读取文件的方法。

答案 1 :(得分:1)

  

如果你的意思是如何做,那就简单地做一些像
 .... def properties = new Properties()
 .... def file = new File(' version.properties')
 .... file.withInputStream {
 ........ properties.load it
 ....}
 .... properties.ProductVersion = ...
 .... properties.ProductBuildDateTime = ...
 .... file.withOuputStream {
 ........ properties.store它,真实的  ....}

答案 2 :(得分:1)

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

csv

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

或者如果你使用竹子,你可以通过让竹子在构建命令中传递这些属性来更容易地做到这一点:

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

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')

现在只需要求Bamboo将这两个参数添加到build命令中,如下所示:

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

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