code hunter
code hunter

Reputation: 21

Invoke a react native method from android native code

I have a method(function) in react native and I want to call that method from android native service class.If it is possible, please help me to solve.

Thanks in advance.

Upvotes: 1

Views: 960

Answers (1)

Maxim Toyberman
Maxim Toyberman

Reputation: 2006

You can send an event from android native code to javascript.

private void sendEvent(ReactContext reactContext,
                       String eventName,
                       @Nullable WritableMap params) {
  reactContext
      .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
      .emit(eventName, params);
}
WritableMap params = Arguments.createMap();
sendEvent(reactContext, "SomeEventName", params);

then in your react-native:

import { DeviceEventEmitter } from 'react-native';


componentWillMount() {
  DeviceEventEmitter.addListener('SomeEventName', function(e: Event) {
    // handle event.
  });
}

  componentWillUnmount () {
    DeviceEventEmitter.removeListener('SomeEventName', this.onModalVisible)
  }

you can see it here on the react-native site : https://facebook.github.io/react-native/docs/native-modules-android

Upvotes: 3

Related Questions