Generating filename based on the android project name and version name when running ant

How to generate a filename based on the android project name and version when running ant, we will look at how the ant scripts should look like after the modifications

If you’ve ever wanted to generate the android project filename according to some data from your android manifest, you can use the ant build scripts to add the functionality needed.

If you don’t have your ant build script in your project directory you can run the following to command to create it along with some of the necessary files required.

android update project -p <android_project_path>

The original ant build script is like this:

<?xml version="1.0" encoding="UTF-8"?>
<project name="android_project_name" default="help">

    <property file="local.properties" />
    <property file="ant.properties" />

    <property environment="env" />
    <condition property="sdk.dir" value="${env.ANDROID_HOME}">
        <isset property="env.ANDROID_HOME" />
    </condition>

    <loadproperties srcFile="project.properties" />

    <fail
            message="sdk.dir is missing. Make sure to generate local.properties using 'android update project' or to inject it through the ANDROID_HOME environment variable."
            unless="sdk.dir"
    />

    <import file="custom_rules.xml" optional="true" />
    <import file="${sdk.dir}/tools/ant/build.xml" />

</project>

So we need to add the following to the ant build script, you can add all this above the line

<import file="${sdk.dir}/tools/ant/build.xml" />

This is the new configuration that you need to add to the ant script

    <xmlproperty
        collapseAttributes="true"
        file="AndroidManifest.xml"
        prefix="mymm" />

    <target name="custom-set-release-mode" >

        <property
            name="out.packaged.file"
            location="${out.absolute.dir}/${ant.project.name}-${mymm.manifest.android:versionName}-release-unsigned.apk" />

        <property
            name="out.final.file"
            location="${out.absolute.dir}/${ant.project.name}-${mymm.manifest.android:versionName}-release.apk" />
    </target>

    <target name="custom-set-debug-files" >

        <property
            name="out.packaged.file"
            location="${out.absolute.dir}/${ant.project.name}-${mymm.manifest.android:versionName}-debug-unaligned.apk" />

        <property
            name="out.final.file"
            location="${out.absolute.dir}/${ant.project.name}-${mymm.manifest.android:versionName}-debug.apk" />
    </target>

    <target
        name="debug"
        depends="custom-set-debug-files, android_rules.debug" />

    <target
        name="release"
        depends="custom-set-release-mode, android_rules.release" />

You can customize the files to provide any combination you want that you can access from either the AndroidManifest.xml or the properties files.