I need to call a native module in MainActivity
's onCreate function by: context.getNativeModule(RNBackgroundToForegroundServiceModule.class)
But I am not sure how to get the current ReactContext
there.
I tried to use (ReactContext) getApplicationContext()
but it crashes.
How can I get the valid ReactContext
?
I came up with the right answer myself.
We have to wait until the Javascript bundle is loaded.
ReactInstanceManager mReactInstanceManager = getReactNativeHost().getReactInstanceManager();
ReactApplicationContext context = (ReactApplicationContext) mReactInstanceManager.getCurrentReactContext();
mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
public void onReactContextInitialized(ReactContext validContext) {
// Use validContext here
}
});
Use this in your ReactActivity:
getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
Just make sure you implemented ReactApplication in your Application class.
IMPORTANT:
It takes time for the ReactContext to be available because there is the UI thread and the JS thread, so in 'onCreate' you can use a Handler with delay of 1 sec for example, the ReactContext should be available:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
ReactContext reactContext = getReactNativeHost().getReactInstanceManager().getCurrentReactContext();
}
}, 1000);
}
But I recommend you do your stuff from a ReactContextBaseJavaModule where the context is provided on creation...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With