Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the current ReactContext in MainActivity's onCreate function?

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?

like image 240
Valeri Avatar asked Mar 07 '18 14:03

Valeri


2 Answers

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
               
            }
        });
like image 56
Valeri Avatar answered Sep 22 '22 13:09

Valeri


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...

like image 25
HedeH Avatar answered Sep 20 '22 13:09

HedeH