Sunday, June 30, 2019

React Native Generate Release APK through Windows Command Prompt Android

This tutorial explains how to generate release APK file through window command prompt in react native application. Full form of APK is Android Package Kit. The APK file is a generated package file containing all the important files which is recommended to run android app on android mobile device. By default when we create react native project app and install that app on our device – Emulator then the app install as Debug Mode. But we cannot get the Signed Release Android APK and without the original APK file we cannot upload this file on Google Play Store.

React Native Generate Release APK through Windows Command Prompt Android


If you want to submit your app on Google Play Store or want to run your final app on other android devices or want to generate release APK or run your app without development server on all android devices then your app must be digitally signed with a certificate. There is also a problem that all the react native beginners is facing that the Un-Signed APK cannot run without the JS server. So using the Singed APK we can run our react native android app to any android mobile device without running the JS Server and upload .APK file to Google Play Store. So in this tutorial we would going to Generate signed release android APK that run without JS Server in React Native in Windows PC using Key Store and lets follow the below steps one by one :

Summary in short : 

  • First of all, we have to generate a Signing key through command prompt.
Note: The command prompt must be run with administrator permission.
  • Place generated Signing key in android/app  ( under your React native project ) folder.
  • Make required entries in android/gradle.properties  file and android/app/build.gradle  file.
  • Run this command to switch directory to android.
  • Command to use : 
    cd android
  • Then run the below command to generate signed version of APK file.
  • Command to use :  
     gradlew assembleRelease 

Generate signed release android APK that run without JS Server in React Native :

Lets follow the below steps to generate signed version APK file in react native application :

Step 1 : Generate Signing key through command prompt.

  • Run command prompt with administrator permission:


  • Just change your PWD( Present Working Directory ) to jdk<version>/bin directory through command prompt.

  • Apply the following command in command prompt and hit ENTER:
keytool -genkey -v -keystore release-key.keystore -alias key-alias -keyalg RSA -keysize 2048 -validity 10000

Note: release-key , key-alias  is the custom name, alias of your keystore file. In my case, I am using release-key , key-alias  as the name, alias of my keystore file. You can use your own custom name, alias of your keystore file according to your requirement.
  • After hit ENTER, the command prompt asks following information:
Enter keystore password:
Re-enter new password:
What is your first and last name?
What is the name of your organizational unit?
What is the name of your organization?
What is the name of your City or Locality?
What is the name of your State or Province?
What is the two-letter country code for this unit?
  • You need to provide mandatory information to proceed further. In our tutorial we have provided below information for reference you can check screenshot and command prompt asks password for key-alias. It allows you to set same password for key-alias as you provide previously or you can set different password for key-alias. we are setting same password for my key-alias.
Note: If you also want to set same password just press ENTER and after hit ENTER your keystore file would be saved under jdk<version>/bin  directory.

  • Once you complete the above steps, then You will get the [Storing release-key.keystore] message If you have done everything correct. You can find this release-key.keystore file under jdk<version>/bin directory.
  • Now you need to cut this keystore file from here and paste into <your-react-native-project-directory>/android/app directory.

Step 2: Open gradle.properties ( <your-react-native-project-directory>/android ) file and make these following required entries.

...
MYAPP_RELEASE_STORE_FILE=release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=key-alias
MYAPP_RELEASE_STORE_PASSWORD=123456
MYAPP_RELEASE_KEY_PASSWORD=123456


Step 3: Open build.gradle ( <your-react-native-project-directory>/android/app ) file and make these following required entries. Make sure below code highlighted in red color should be present in build.gradle file

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }    

    defaultConfig {
        applicationId "com.rnv59"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
   
    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
            }
        }
    } 

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    implementation project(':@react-native-community_slider')
   
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}


Step 4: Change your PWD( Present Working Directory ) to your react native project directory and apply the below command in command prompt to switch to android directory.
cd android

Step 5: Apply the below command to generate signed version of APK file. 
gradlew assembleRelease

Note: Must close the node js server before applying the above command.

  • After successfully completed the process of generating the release version of your APK, you will get the following output.

  • Build generated successfully :

  • You will get your released signed APK under <your-react-native-project-directory>/android/app/build/outputs/apk/release directory.


Now, you can run this app-release.apk file into any android mobile device and submit this app-release.apk file on Google Play Store.

You can test the signed apk on your android device connected with your system, by simply running the code below.
react-native run-android --variant=release

Also you can create debug APK :
cd android
gradlew assembleDebug

This is all about React Native Generate Release APK through Windows Command Prompt Android. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment