rn-heartbeat
rn-heartbeat copied to clipboard
Sending information to React Native level from the service
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 did you get any solution?
@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 Androidstudio gives me an error: Cannot resolve symbol 'context'
how do you solve it?