CodePush in React Native (Android)

·

6 min read

CodePush in React Native (Android)

What is CodePush?

Code push generally refers to the process of updating or deploying code changes to a live server or application without requiring the users to download or reinstall the entire application. It's a way to push updates seamlessly, reducing downtime and providing a smoother user experience.

In the context of React Native, there is a specific tool called Microsoft App Center CodePush. This tool allows developers to push updates to their React Native apps without going through the traditional app store update process. The benefits include:

  1. Faster Updates: Users get the latest features, bug fixes, and improvements without waiting for app store approvals.

  2. Reduced Downtime: Code push allows for quick bug fixes or critical updates without taking the app offline or forcing users to download a new version.

  3. Cost-Efficiency: By avoiding app store updates, developers save time and resources associated with the submission and approval process.

  4. A/B Testing: Developers can experiment with different features or changes in real-time and gather user feedback without the need for app store updates.

  5. Fallback Mechanism: If an update fails, the app can fall back to the previous version, ensuring a more reliable deployment process.

Note: CodePush is Microsoft solution to update javascript portion, Native iOS and Android code can't update

Implementation of Code Push in React Native

Microsoft App Center :

Create an account on Microsoft App Center if you don't have one. This is where you'll manage your CodePush deployments.

To Create Microsoft App Center Account you can follow this link https://appcenter.ms/sign-in?original_url=%2Fapps

Now, after signing in to the App Center we will see how can we add our app in it.

Adding a New App to App Center:

  1. Dashboard:

    After logging in, you'll be directed to the App Center dashboard.

  2. Create a New App:

    Click on the "Add new" or "Create" button to add a new app.

  3. Select Platform:

    Choose the platform of your app (e.g., React Native for a mobile app).

  4. Enter App Details:

    Enter the required details for your app, including the app's name.

  5. Organization Selection:

    If you are part of multiple organizations, select the appropriate organization for the app.

  6. Choose Operating System:

    Specify the operating system your app is built for (iOS, Android, or both).

  7. Create App:

    Click on the "Create" or "Save" button to create the app.

  8. App Dashboard:

    You'll be redirected to the dashboard for the newly created app.

  9. App Secret:

    Retrieve the App Secret from the app's settings. This secret is needed for integrating App Center services into your React Native app.

  10. Deployment Keys:

    Generate deployment keys for different environments (e.g., Staging, Production). These keys are required for CodePush integration.

Now you have successfully created an account on App Center and added a new app. Make sure to keep your App Secret and deployment keys secure, as they are crucial for integrating App Center services into your React Native project.

Linking App Center in React Native :

On the dashboard of the App Center you will get a command for adding SDK to the project. Now open your react native project in VS-Code and follow below given steps.

Crash and Analytics to your app:

npm install appcenter appcenter-analytics appcenter-crashes --save-exact

Integrate the SDK:

Create a new file with the filename appcenter-config.json in android/app/src/main/assets/ (createassetsfolder if not available) with the following content.

{
"app_secret": "SECRET_KEY GIVEN ON APP CENTER DASHBOARD"
}

Modify the app's res/values/strings.xml to include the following lines:

<string name="appCenterCrashes_whenToSendCrashes" moduleConfig="true" translatable="false">DO_NOT_ASK_JAVASCRIPT</string>
<string name="appCenterAnalytics_whenToEnableAnalytics" moduleConfig="true" translatable="false">ALWAYS_SEND</string>

Installing AppCenter Cli in Project:

In terminal run the following command to install appcenter:

npm install -g appcenter-cli

Now, Install React Native CodePush Package from npm

npm i react-native-code-push

Plugin Installation and Configuration for React Native 0.60 version and above

  1. In your android/settings.gradle file, make the following additions at the end of the file:

     include ':app', ':react-native-code-push'
     project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')
    
  2. In your android/app/build.gradle file, add the given line of code as an additional build task definition to the end of the file:

     apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
    
  3. Update the MainApplication.java file to use CodePush via the following changes:

     ...
     // 1. Import the plugin class.
     import com.microsoft.codepush.react.CodePush;
    
     public class MainApplication extends Application implements ReactApplication {
    
         private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
             ...
    
             // 2. Override the getJSBundleFile method in order to let
             // the CodePush runtime determine where to get the JS
             // bundle location from on each app start
    
            //You have to add this section given below
             @Override
             protected String getJSBundleFile() {
                 return CodePush.getJSBundleFile();
             }
         };
     }
    
  4. Add the Deployment key to res/values/strings.xml:

     //Inside resources 
     <resources>
          <string moduleConfig="true" name="CodePushDeploymentKey">DEPLOYMENT_KEY</string>
      </resources>
    

    For the DEPLOYMENT_KEY, navigate to the App Center Dashboard. On the left panel, click on 'Distribute,' and then select 'CodePush.' Locate the 'Create Standard Deployments' button on the main screen.

    Next, you'll find a dropdown on the right corner of the screen. Choose 'Production' (if you are working on a production app). Next to the dropdown, there's a settings button; click on it. You'll find the Production and Staging Keys there. Copy the key you need and add it to the provided code.

  5. In App.js:

    import CodePush from "react-native-code-push";

    and after that pass your App.js component to higher order function of CodePush like this:

     import CodePush from "react-native-code-push";
    
     const MyApp = () => {
     }
    
     export default CodePush(MyApp);
    

    Now the CodePush Setup is completed, you have to now login to the code push from terminal

     //Run the given command in terminal to login app center
     appcenter login
    

    It will then redirect you to the browser, allowing you to log in to your App Center account. Afterward, it will provide you with a SECRET_CODE. Paste this code into the terminal when prompted with: '? Access code from browser: SECRET_CODE'"

    Finally you are logged in to the App Center inside your project.

There are some key points to be keep in mind before deploying the changes:

  1. In android/gradle.properties add the version for the app like this

     ANDROID_BUILD_VERSION_NAME= 1.0
    

    Keep in mind to give version name using one point not like 0.1.1 / 0.1.1.1.

    It should be like 1.0/ 0.1 / 1.2 ...... etc

  2. In android/app/build.gradle/ add the version of app like :

     defaultConfig {
             versionCode 1
             versionName ANDROID_BUILD_VERSION_NAME
             ndk {
                 abiFilters 'arm64-v8a', 'armeabi-v7a'
                 }
         }
    

Now, generate the APK for your React Native project, install it on your device, or publish it to the Play Store. It is synced with CodePush."

For generating APK you can refer to : https://reactnative.dev/docs/signed-apk-android

Run the following command in the terminal if you want to make any changes in the current version of your app, and your app will get updated without updating it from the Play Store.

appcenter codepush release-react -a <ownerName>/MyApp-Android

"You will find the above command in your App Center's dashboard during setup."

Thanks for Reading!

I hope you found this blog on implementing CodePush in React Native helpful and informative. If you have any questions, suggestions, or just want to chat about React Native development, feel free to reach out. Happy coding!

Connect with me:https://www.linkedin.com/in/mohd-saif-134076141/

Stay tuned for more React Native insights and tutorials. Don't forget to subscribe for updates!

Cheers,
Saif Siddiqui