ABSYZABSYZ
  • Home
  • About Us
  • Our Services
    • Consulting Services
    • Managed Services
    • Implementation Services
    • Staffing Services
  • Our Approach
  • Products

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

  • White papers

    Trends We Explored

ABSYZ

Communication Between Native And React Native Android

Home / Article & Blogs / Web Design / Mobile Development / Communication Between Native And React Native Android
By Pravallika Damerla inMobile Development

Communication between native and React Native components in Android is a crucial aspect of app development. React Native is undoubtedly a powerful tool for creating applications on both Android and iOS platforms. However, despite its comprehensiveness, there are instances where certain components must be developed natively to gain more granular control over their behavior. 

In such scenarios, when we blend native and React Native components within the same application, the need for seamless communication between these two worlds arises. Ensuring a smooth interaction between these distinct parts becomes essential to achieve a cohesive and fully functional application. By establishing effective communication channels, developers can leverage the strengths of both approaches and deliver a superior user experience.

Communication from android to React-native:

Suppose we have a back button placed on the action bar of an Android application, and there’s a specific action that needs to be executed in the React Native codebase upon clicking this button. To achieve this seamless interaction, a communication bridge is essential. 

The communication bridge serves as a crucial link between the native Android code and the React Native components. It facilitates the exchange of information and events between these two distinct parts of the application. When the back button is clicked, the bridge enables the transmission of this event to the React Native environment, triggering the necessary action or function. This way, the application can efficiently coordinate actions and responses across the native and React Native realms, ensuring a smooth and cohesive user experience. Let’s create a bridge between the native Android code and React Native components by following these steps:

Step 1:

  1. Create one java class and extend it from ReactContextBaseJavaModule
  2. Write one constructor
  3. override getName method
public class AndroidReactNativeBridgeModule extends ReactContextBaseJavaModule implements   LifecycleEventListener{
private static ReactApplicationContext reactApplicationContext;
private final ActivityEventListener mActivityEventListener = new     BaseActivityEventListener();
AndroidReactNativeBridgeModule(ReactApplicationContext reactContext) {
super(reactContext);
 reactApplicationContext = reactContext;
 reactApplicationContext.addLifecycleEventListener(this);
 reactApplicationContext.addActivityEventListener(mActivityEventListener);
   }
  @Override
  public void onHostResume() {
   // Activity `onResume`
    }
    @Override
     public void onHostPause() {
     // Activity `onPause`
     }
     @Override
     public void onHostDestroy() {
     // Activity `onDestroy`
      }
   @Override
   public String getName() {
   return "AndroidReactNativeBridgeModule";
    }
    @ReactMethod
    public String getSDKName() {
     System.out.println("Greetings from Java");
      return "AndroidReactNativeBridgeModule";
     }

Step 2:

Create a new module file and extend from ReactPackage, override createNativeModules and add modules created in the previous step in the array list.

 public class AndroidReactNativeBridgePackage implements ReactPackage {
   @Override
   public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
       List<NativeModule> modules = new ArrayList<>();
       modules.add(new AndroidReactNativeBridgeModule(reactContext));
       return modules;
   }
   @Override
   public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
       return Collections.emptyList();
    }

  }

Step 3:

Go to Application class and add package created in previous step, in getPackage method

public class MainApplication extends Application implements ReactApplication {
  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
     @Override
     public boolean getUseDeveloperSupport() {
        return BuildConfig.DEBUG;
     }
     @Override
     protected List<ReactPackage> getPackages() {
        @SuppressWarnings("UnnecessaryLocalVariable")
        List<ReactPackage> packages = new PackageList(this).getPackages();
        // Packages that cannot be autolinked yet can be added manually here, for example:
        // packages.add(new MyReactNativePackage());
        packages.add(AndroidReactSDKManager.getInstance().getReactPackage());
        return packages;
     }
     @Override
     protected String getJSMainModuleName() {
        return "index";
     }
  };

Step 4:

In the ReactNative project, open index.js file and import module.

Import { NativeModules } from ‘react-native’
Module.exports = NativeModules.AndroidReactNativeBridgeModule;

Step 5:

In the android file write this to trigger the event  in the back button natively (android)

WritableMap params = Arguments.createMap();
params.putString(“eventProperty”,”someValue”);
ReactApplication rnApp = (ReactApplication) getApplicationContext();
rnApp.getReactNativeHost().getReactInstanceManager().getCurrentReactContext().getJSModule(DeviceEventManagerModule.RXTDeviceEmitter.class).emit(“BackActionTrigger”,Arguments.createMap());

Step 6:

In  the react native component , we can add this code as mentioned below.

If (Platform.OS == ‘android’)
{
Const eventEmitter = new NativeEventEmitter(NativeModules.AndroidReactNativeBridge)
eventEmitter.addListener(‘BackActionTrigger’,(event) => {
console.log(‘event.eventProperty’,event.eventProperty)
})
}

Reference: https://reactnative.dev/docs/communication-android

Conclusion:

Additionally, this seamless communication between native and React Native components in Android allows developers to create highly interactive and dynamic applications, where both technologies complement each other flawlessly. By breaking down the barriers and leveraging the communication bridge effectively, the development process becomes more efficient, leading to faster iterations and improved collaboration among the development team.

Furthermore, as mobile app development evolves, having expertise in both native and React Native environments and understanding their communication intricacies becomes a valuable asset. Developers who can navigate and optimize this communication bridge effectively can build versatile applications that cater to a broader audience, ensuring a competitive edge in the ever-evolving app market. Embracing this cohesive approach not only streamlines development but also paves the way for innovative and engaging user experiences.

get in touch
communication between native and react native android
88
Like this post
5 Posts
Pravallika Damerla

Search Posts

Archives

Categories

Recent posts

Einstein For Developers: Get Started Now

Einstein For Developers: Get Started Now

<strong>K-Means Clustering: Exploring and Clarifying Its Enigmatic Nature</strong>

K-Means Clustering: Exploring and Clarifying Its Enigmatic Nature

Dreamforce 2023: What To Expect

Dreamforce 2023: What To Expect

Salesforce Einstein GPT: Generative AI Transforming Customer Experiences

Salesforce Einstein GPT: Generative AI Transforming Customer Experiences

Redux In React Native: A Complete Guide

Redux In React Native: A Complete Guide

  • A Look Back At ABSYZ's Awards & Achievements
    Previous PostA Look Back At ABSYZ's Awards & Achievements
  • Next PostRedux In React Native: A Complete Guide
    A Look Back At ABSYZ's Awards & Achievements

Related Posts

Redux In React Native: A Complete Guide
Mobile Development

Redux In React Native: A Complete Guide

Hive Database Integration In Flutter
Flutter Mobile Development

Hive Database Integration In Flutter

GetConnect: The best way to perform API operations in Flutter with GetX.
Flutter Mobile Development

GetConnect: The best way to perform API operations in Flutter with GetX.

How to Add an iOS Native Framework in the Flutter Project?
Mobile Development Web Design

How to Add an iOS Native Framework in the Flutter Project?

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE | CANADA

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT