Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native (Android Native Module): Get access to ReactContext in another Class?

I want to call a method in MyCustomModuleClass extends ReactContextBaseJavaModule from another Class

MyCustomModule.java

public class MyCustomModule extends ReactContextBaseJavaModule {

  private ReactContext mReactContext;

  public MyCustomModule(ReactApplicationContext reactContext) {
    super(reactContext);
    mReactContext = reactContext;
  }

  @Override
  public String getName() {
    return "CustomModule";
  }


    private void sendEvent(String eventName, Object params) {
        mReactContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, params);
    }    
}

I'm trying this..

OtherClass.java

public class OtherClass extends AnotherClass {

    @Override
    protected void eventOccurred(Context context) {
        MyCustomModule RNC = new MyCustomModule(?);//-> Can't call without ReactContext
        RNC.sendEvent("CustomEvent", ObjectData); 
    }   
}

Sorry, I know nothing about java, could any one please help me out?

Is there any way I can get ReactContext in OtherClass?

like image 519
antihate Avatar asked Feb 08 '16 20:02

antihate


1 Answers

Here's how I did it in a FirebaseMessagingService extended class.

public class MyPushListener extends FirebaseMessagingService {

  @Override
  public void onMessageReceived(JSONObject message, JSONObject content){

    MainApplication application = (MainApplication) this.getApplication();

    ReactNativeHost reactNativeHost = application.getReactNativeHost();
    ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
    ReactContext reactContext = reactInstanceManager.getCurrentReactContext();

    if (reactContext != null) {
      WritableNativeArray params = new WritableNativeArray();
      params.pushString(message.toString());
      reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
          .emit("EVENT_HAS_TRIGGERED", params);
    }
  }
}

Source

like image 183
reflexgravity Avatar answered Sep 20 '22 09:09

reflexgravity