Reputation: 1142
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
?
Upvotes: 10
Views: 17021
Reputation: 1
it's work for me with answer 4
mReactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
public void onReactContextInitialized(ReactContext validContext) {
// Use validContext here
WritableMap params = Arguments.createMap();
sendEvent(validContext, "appStateChange", params);
}
});
Upvotes: -1
Reputation: 1142
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
}
});
Upvotes: 14
Reputation: 3034
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...
Upvotes: 9