Build your Android APK with the Manifest Version Number

I’ve been setting up Jenkins CI at work for all our mobile platforms (which is awesome) but one problem I encountered with our android deployments was that the default APK file names were simply ProjectName-release.apk. I wanted to have the build process add the version number to the APK file but locating the file after the build and renaming it was a lame solution. Instead, I wanted the Android build process to use the right file name from the start so I thought I’d share how I did it.

First I set up the project to use Ant as outlined in the Building and Running from the Command Line Google docs. This allows you to use ant release to build your project without eclipse (Jenkins has ant integration as well). The most recent version of the Android SDK also allows you to include a custom_rules.xml for your custom Ant build rules. These are imported by the build.xml file and executed in the Ant build process. Here’s the custom rules I created to add the version number from the AndroidManifest.xml to the apk file name:

<?xml version="1.0" encoding="UTF-8"?>
<project>

	<target name="rename-release-with-version-number">
		<xmlproperty file="AndroidManifest.xml" 
					 prefix="themanifest" 
					 collapseAttributes="true"/>
		
		<!--  see ${sdk.dir}/tools/ant/build.xml -set-release-mode -->
		<property name="out.packaged.file" 
		          location="${out.absolute.dir}/${ant.project.name}-${themanifest.manifest.android:versionName}-release-unsigned.apk" />
		<property name="out.final.file" 
		          location="${out.absolute.dir}/${ant.project.name}-${themanifest.manifest.android:versionName}-release.apk" />
	</target>
	<target name="-set-release-mode"
		 depends="rename-release-with-version-number,android_rules.-set-release-mode">
		<echo message="target: ${build.target}"></echo>
	</target>

</project> 

The -set-release-mode target overrides the same target in ${sdk.dir}/tools/ant/build.xml where the out.final.file file name is originally defined. To add the version number, I override -set-release-mode by calling my rename-release-with-version-number target in the dependencies and then calling the original android_rules.-set-release-mode to finish any other setup there.

The rename-release-with-version-number target simply reads in the manifest and adds the version number to both out.final.file and out.packaged.file.

Now the build APK is ProjectName-version-release.apk and it’s automatically used by the rest of the ant build process without clumsy file renaming.