Is there any callback for android when ReactContext is created in MainAcitivity?
I checked that it is very strange that ReactInstanceManager.getCurrentReactContext in MainActivity would return null in onCreate and in onResume as well. I found that it should have been created in initializeReactContext() inside ReactInstanceManager, which is called when mReactRootView.initializeReactContext() is invoked.
Yet the context is still null, any hints?
I'm gettting the same issue when trying to track Android AppState. I've added a SO question here: http://stackoverflow.com/questions/35041962/react-native-android-reactcontext-returning-null
Hope this is solvable!
Hi @yychun1217 - I have created this solution for returning AppState (i.e. active or background) in Android today. Perhaps you can adapt it for your needs?
https://github.com/scgough/appstateandroid
You get the context in constructor of native modules. So there is really no reason you should need it in onCreate of an activity.
Closing this as tese kinds of questions are more suited towards stackoverflow.
On another note, AppState is in master now - https://github.com/facebook/react-native/commit/c2d75d7a65a2bdf6e1e24a9ce887f9492be477de
I think it's worth to reopen it, any kind of a such callback would be useful
@pvllnspk What's your use case?
f.e. send an initial event to js like 'show me ''Loading' title'
@pvllnspk
An initial event? Not sure I understand.
If you're talking about Resume you can get that by listening for the host activity easily enough through a native module or a package like rn-device-activity
If you're talking about really just wanting a way to show a loading screen while JS is loading you probably want a JS-controlled splash screen with something like rn-splash-screen
I had the same problem with ReactContext being null up to a few seconds after my app started. Since I needed to emit an event to JS as soon as possible, I ended up with random crashes on startup due to a null ReactContext object. To avoid the race condition caused by ReactNative starting up, you can listen to the onReactContextInitialized callback.
First, make your Activity/Fragment implement ReactInstanceManager.ReactInstanceEventListener, then add itself as a listener:
@Override
public void onResume() {
super.onResume();
getReactInstanceManager().addReactInstanceEventListener(this);
}
@Override
public void onPause() {
super.onPause();
getReactInstanceManager().removeReactInstanceEventListener(this);
}
When your ReactContext is created, the callback will be notified:
@Override
public void onReactContextInitialized(ReactContext context) {
Log.d(TAG, "Here's your valid ReactContext");
}
@lucas-tulio Why hooking to onResume/onPause and not to onCreate/onDestory?