Android Signing per Flavors with Gradle

okuzawats
okuzawats

I think you sometimes want to sign Android APK with different keystore per build flavors. You can do this with signingConfigs and buildTypes of app/build.gradle.

First, define signingConfigs inside android block of your app/build.gradle as many as the number of signings. Inside the signingCofigs block, load storeFile and keys. Maybe from .properties file when you build APK in your local or environmental variables when you build APK in CI server.

android {
    // omitted
    signingConfigs {
        dev {
            storeFile = // TODO
            storePassword // TODO
            keyAlias // TODO
            keyPassword // TODO
        }
        stg {
            storeFile = // TODO
            storePassword // TODO
            keyAlias // TODO
            keyPassword // TODO
        }
        prd {
            storeFile = // TODO
            storePassword // TODO
            keyAlias // TODO
            keyPassword // TODO
        }
    }
    // omitted
}

Secondly, define productFlavors as always.

android {
    // omitted
    flavorDimensions 'default'
    productFlavors {
        dev {
            dimension "default"
            applicationIdSuffix ".dev"
        }
        stg {
            dimension "default"
            applicationIdSuffix ".stg"
        }
        prd {
            dimension "default"
        }
    }
    // omitted
}

Lastly, define signingConfigs per the flavors defined in buildTypes block. productFlavors.yourflavor.signinfConfig is the signing configuration for the flavor. signingConfigs.config is the signing configuration defined in signingConfigs.

android {
    // omitted
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }

        release {
            productFlavors.dev.signingConfig signingConfigs.dev
            productFlavors.stg.signingConfig signingConfigs.stg
            productFlavors.prd.signingConfig signingConfigs.prd
        }
    }
    // omitted
}

I guess now you can sign APK with different keystore for different flavors. Maybe buildTypes block should be defined after signingConfigs block and productFlavors block.

android {
    signingConfigs {
        // omitted
    }

    flavorDimensions 'default'
    productFlavors {
        // omitted
    }

    buildTypes {
        // omitted
    }
}

Thanks @RyuNen344.