How to customize the APK file name for product flavors?

JJD picture JJD · Aug 3, 2014 · Viewed 24.5k times · Source

I am customizing the name of the APK file of my Android application within the build.gradle script as follows:

android {
    defaultConfig {
        project.ext.set("archivesBaseName", "MyApplication");
    }
}

Now that I am using product flavors:

android {
    productFlavors {
        green {
            applicationId "com.example.myapplication.green"
        }

        blue {
            applicationId "com.example.myapplication.blue"
        }
    }
}

Is there a way to customize the name of each APK? I experimented with archiveBaseName and baseName without success. In the end I want to come up with the following files:

build/outputs/apk/Blue-debug-1.2.1.apk
build/outputs/apk/Blue-debug-unaligned.apk
build/outputs/apk/Blue-release-1.2.1.apk
build/outputs/apk/Blue-release-unaligned.apk
build/outputs/apk/Green-debug-1.2.1.apk
build/outputs/apk/Green-debug-unaligned.apk
build/outputs/apk/Green-release-1.2.1.apk
build/outputs/apk/Green-release-unaligned.apk

Answer

Lakshman Chilukuri picture Lakshman Chilukuri · Aug 4, 2014

Try to put this in your android closure of build.gradle

buildTypes {
    debug {
        // debug buildType specific stuff
    }
    release {
        // release buildType specific stuff
    }
    applicationVariants.all { variant ->
        if (variant.buildType.name.equals("release") &&
            variant.productFlavors[0].name.equals("green") &&
            variant.zipAlign) {
                def apk = variant.outputFile;
                variant.outputFile = new File(apk.parentFile, "green.apk");
        } else if(variant.buildType.name.equals("release") &&
            variant.productFlavors[0].name.equals("blue") &&
            variant.zipAlign) {
                def apk = variant.outputFile;
                variant.outputFile = new File(apk.parentFile, "blue.apk");
        }
    }
}

Now the outputs should be like green.apk and blue.apk.