Two Way Communication between React Native and Android Native – Part 2
- General
Two Way Communication between React Native and Android Native – Part 2
Two Way Communication between React Native and Android Native – Part 2
In this section we will see how to Communicate from Android to React Native. If you are looking from communication from React Native to Android, Please refer to This Blog.
So Lets start.
Communication from Android to React Native is done by Events. It is like Android will send events and React Native will observe the event and reacts to it.
Lets understand it by performing a simple Task. Lets call a function written in React Native from Android Native button.
Step 1: Creating a JS file in React Native to Manage Event Listeners
1 2 3 4 5 6 7 8 9 10 |
//EventListerner.js import {DeviceEventEmitter} from 'react-native'; export const initEventListener = () => { DeviceEventEmitter.addListener('fun1', function (e: Event) { // handle event and you will get a value in event object, you can log it herec console.log('Fun1 Event Called'); console.log(e); }); }; |
Step 2: Call Event from Android Native
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Button button2 = findViewById(R.id.button2); button2.setOnClickListener(v -> { //Setting Value to Pass to React Native Event WritableMap map = Arguments.createMap(); map.putString("key1", "Value1"); map.putString("key2", "Value2"); try { getReactInstanceManager().getCurrentReactContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("fun1", map); } catch (Exception e){ Log.e("ReactNative", "Caught Exception: " + e.getMessage()); } }); |
From Part 1 we have seen that we can create an Activity in Android Native and open that Activity from React Native. Now on that Activity place a button and write the button onClickListener Event.
Inside onClickListerner, we have the first part where we are creating the Map object to send data.
1 2 3 |
WritableMap map = Arguments.createMap(); map.putString("key1", "Value1"); map.putString("key2", "Value2"); |
In the other part we are generating an event with name fun1 and passing map object.
1 2 3 4 5 6 7 8 |
try { getReactInstanceManager().getCurrentReactContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit("fun1", map); } catch (Exception e){ Log.e("ReactNative", "Caught Exception: " + e.getMessage()); } |
This will be listen by React Native code which we have written in Step 1 and execute it. Now our React Native have the control to execute. By using the data and different events we can do different task as per our requirements.
Hope now you have better understanding of how to setup communication between Android Native and React Native.
You can refer the source code from the following link
https://hiteshsinghal@bitbucket.org/aurigait/reactnativeandroidcommunication.git
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s