Auto increment version code in Android app

2019-01-12 16:03发布

is there a way to auto-increment the version code each time you build an Android application in Eclipse?

According to http://developer.android.com/guide/publishing/versioning.html, you have to manually increment your version code in AndroidManifest.xml.

I understand, you have to run a script before each build which would, e.g. parse AndroidManifest.xml file, find the version number, increment it and save the file before the build itself starts. However, i couldn't find out how and if Eclipse supports runnings scripts before/after builds.

I have found this article about configuring ant builder, but this is not exactly about Android and I fear this will mess up too much the predefined building steps for Android?

Should be a common problem, how did you solve it?

Well, one can do this manually, but as soon as you forget to do this chore, you get different versions with the same number and the whole versioning makes little sense.

14条回答
何必那么认真
2楼-- · 2019-01-12 16:12

Building on Rocky's answer I enhanced that python script a bit to increase also versionCode, works for me on Eclipse (integrated as per ckozl great tutorial) & Mac OSX

#!/usr/bin/python
from xml.dom.minidom import parse

dom1 = parse("AndroidManifest.xml")
oldVersion = dom1.documentElement.getAttribute("android:versionName")
oldVersionCode = dom1.documentElement.getAttribute("android:versionCode")
versionNumbers = oldVersion.split('.')

versionNumbers[-1] = unicode(int(versionNumbers[-1]) + 1)
dom1.documentElement.setAttribute("android:versionName", u'.'.join(versionNumbers))
dom1.documentElement.setAttribute("android:versionCode", str(int(oldVersionCode)+1))
with open("AndroidManifest.xml", 'wb') as f:
    for line in dom1.toxml("utf-8"):
        f.write(line)

also don't forget to chmod +x autoincrement.py and make sure you have correct path to python on the first line (depending on your environment) as sulai pointed out

查看更多
虎瘦雄心在
3楼-- · 2019-01-12 16:13

FWIW, I was able to update the build version value in six lines of python:

#!/bin/env python
import os
from xml.dom.minidom import parse
dom1 = parse("AndroidManifest.xml")
dom1.documentElement.setAttribute("android:versionName","%build.number%")
f = os.open("AndroidManifest.xml", os.O_RDWR)
os.write( f, dom1.toxml() )
查看更多
相关推荐>>
4楼-- · 2019-01-12 16:13

If you're using gradle then you can specific versionName and versionCode very easy in build.gradle. You can use git commit count as an increasing number to identify the build.

You can also use this library: https://github.com/rockerhieu/Versionberg.

查看更多
贪生不怕死
5楼-- · 2019-01-12 16:14

I've done something similar but written it as a Desktop AIR app instead of some external C# (didn't feel installing another build system). Build this Flex/ActionScript app and change the path to your file, the build it as a standalone desktop app. It rewrites the 1.2.3 part of your file.

    <?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
                       xmlns:s="library://ns.adobe.com/flex/spark"
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       width="371" height="255" applicationComplete="Init();">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[

            public function Init():void
            {
                import flash.filesystem.File;
                import flash.filesystem.FileMode;
                import flash.filesystem.FileStream;

                var myFile:File = new File("D:\\Dropbox\\Projects\\My App\\src\\Main-app.xml");

                var fileStream:FileStream = new FileStream();
                fileStream.open(myFile, FileMode.READ);

                var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable);

                var startIndex:Number = fileContents.indexOf("<versionNumber>");
                var numberIndex:Number = startIndex + 15;
                var endIndex:Number = fileContents.indexOf("</versionNumber>");

                if (startIndex == -1 || endIndex == -1)
                    return;

                var versionNumber:String = fileContents.substr(numberIndex, endIndex - numberIndex);
                var versionArr:Array = versionNumber.split(".");
                var newSub:Number = Number(versionArr[2]);
                newSub++;
                versionArr[2] = newSub.toString();
                versionNumber = versionArr.join(".");

                var newContents:String = fileContents.substr(0, startIndex) + "<versionNumber>" + versionNumber + "</versionNumber>" +
                                fileContents.substr(endIndex + 16);
                fileStream.close(); 


                fileStream = new FileStream();
                fileStream.open(myFile, FileMode.WRITE);
                fileStream.writeUTFBytes(newContents);
                fileStream.close(); 

                close();
            }
        ]]>
    </fx:Script>
    <s:Label x="10" y="116" width="351" height="20" fontSize="17"
             text="Updating My App Version Number" textAlign="center"/>

</s:WindowedApplication>
查看更多
够拽才男人
6楼-- · 2019-01-12 16:15

Building on Charles' answer, the following increments the existing build version:

#!/usr/bin/python
from xml.dom.minidom import parse

dom1 = parse("AndroidManifest.xml")
oldVersion = dom1.documentElement.getAttribute("android:versionName")
versionNumbers = oldVersion.split('.')

versionNumbers[-1] = unicode(int(versionNumbers[-1]) + 1)
dom1.documentElement.setAttribute("android:versionName", u'.'.join(versionNumbers))

with open("AndroidManifest.xml", 'wb') as f:
    for line in dom1.toxml("utf-8"):
        f.write(line)
查看更多
Summer. ? 凉城
7楼-- · 2019-01-12 16:15

For those that are on OSX and want to use Python, but not loose the XML formatting which when parsing is done by the python XML parser happens, here is a python script that will do the incremental based on regular expression, which keeps the formatting:

#!/usr/bin/python
import re

f = open('AndroidManifest.xml', 'r+')
text = f.read()

result = re.search(r'(?P<groupA>android:versionName=")(?P<version>.*)(?P<groupB>")',text)
version = str(float(result.group("version")) + 0.01)
newVersionString = result.group("groupA") + version + result.group("groupB")
newText = re.sub(r'android:versionName=".*"', newVersionString, text);
f.seek(0)
f.write(newText)
f.truncate()
f.close()

The code was based on @ckozl answer, just was done in python so you don't need to create an executable for this. Just name the script autoincrement.py, place it in the same folder with the manifest.xml file and then do the steps that ckozl did describe above!

查看更多
登录 后发表回答