'How to use reactContext and getJSModule in a service?

I have a ReactModule which it turn starts a ForegroundService which registers and listens for some events. Once one of the events happens I want to send a message to the React-Native level using DeviceEventManagerModule...

reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(DRIVING_EVENT, params);

The service has it's own context, and it doesn't have the getJSModule method there. Is there a way I can get the reactContext inside my service?

I think that I can use Broadcasts to send events from the service to the calling module, but if the application is swiped out from recent apps - will the module still be able to listen to the broadcasts?



Solution 1:[1]

Try this.

public class YourModuleName extends ReactContextBaseJavaModule {
    
  private final ReactApplicationContext _reactContext;
    
  public YourModuleName(ReactApplicationContext reactContext) {
        super(reactContext);
        _reactContext = reactContext;
  }

  // Your code here...

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gonzalo Locascio