How to sign an apk through command line

Ahamed Husain picture Ahamed Husain · Jun 5, 2018 · Viewed 22.4k times · Source

Be informed that we have created an apk file through command line with the help of Android SDK. Now since uploading it to google play store needs the apk to be signed. How shall we do this.

Answer

jomis picture jomis · Jun 5, 2018

Step 1

First you need to generate a private signing key

keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

This command will prompt you for a password for your keystore and key (also for some additional fields). Please remember to keep your keystore file private at anytime.

Step 2

Next you need to setup gradle

  1. Place my-release-key.keystore which you generated in Step 1 under android/app
  2. Update your ~/.gradle/gradle.properties under android/app and add the following

    MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
    MYAPP_RELEASE_KEY_ALIAS=my-key-alias
    MYAPP_RELEASE_STORE_PASSWORD=<The password you choose earlier with the keytool>
    MYAPP_RELEASE_KEY_PASSWORD=<The password you choose earlier with the keytool>
    

Step 3

Finally you need to update your android/app/build.gradle.

android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}

Now you can simply generate a signed release via the command line by running the following command in your android directory

./gradlew assembleRelease

The generated apk can then be found under your build/outputs/apk/release directory.