rn-heartbeat icon indicating copy to clipboard operation
rn-heartbeat copied to clipboard

Sending information to React Native level from the service

Open edwardkes opened this issue 2 years ago • 3 comments

Hi, in your article you did something like this:

public class HeartbeatService extends Service {
   …
   private Handler handler = new Handler();
   private Runnable runnableCode = new Runnable() {
     @Override
     public void run() {
       context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("Heartbeat",null);
       handler.postDelayed(this, 2000);
     }
   };
   …
}

But the context you use, here is service context and it doesn't have getJSModule() method. So how does it work for you? I get an error complaining that this method doesn't exist on this context. Can you please explain how does it work for you?

edwardkes avatar Mar 31 '22 09:03 edwardkes

@edwardkes did you get any solution?

uplsoumen avatar May 31 '22 12:05 uplsoumen

@uplsoumen Sorry for replying so late. But I have indeed...

You can get the React context like that:

ReactApplication application = (ReactApplication)(context.getApplicationContext());
ReactContext reactContext = application.getReactNativeHost()
                .getReactInstanceManager()
                .getCurrentReactContext();

If the context is null, than you can request it like that:

 ReactApplication application = (ReactApplication)(context.getApplicationContext());
  application
                .getReactNativeHost()
                .getReactInstanceManager()
                .addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
                    @Override
                    public void onReactContextInitialized(ReactContext context) {
                        Log.i(TAG, "onReactContextInitialized: received new react context");

                    }
                });
            application.getReactNativeHost()
                    .getReactInstanceManager()
                    .createReactContextInBackground();

edwardkes avatar Feb 26 '23 16:02 edwardkes

@edwardkes Androidstudio gives me an error: Cannot resolve symbol 'context'

how do you solve it?

soadtechdev avatar May 16 '23 16:05 soadtechdev