How can I get the current ReactContext in MainActivity's onCreate function?
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...