React Native(Android Native Module):在另一个Class中访问ReactContext?

时间:2016-02-08 20:25:56

标签: java android react-native

我想在MyCustomModuleClass中调用一个方法从另一个类中扩展ReactContextBaseJavaModule

  

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);
    }    
}

我正在尝试这个..

  

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); 
    }   
}

对不起,我对java一无所知,有人可以帮帮我吗?

有没有办法在OtherClass中获得ReactContext?

1 个答案:

答案 0 :(得分:0)

这是我在FirebaseMessagingService扩展类中的做法。

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