As the React-Native AppState API is iOS only I'm writing an appState event emitter for the Android side of my app. In the app's MainActivity on the Java side, I want to emit from the onResume and onPause functions to tell the JS side over the bridge that my app is either in the foreground or background
At the moment, I can minimise my app (and go back to the home-screen on my device) and the background event is emitted correctly. However, when I resume my app nothing is fired...also nothing is fired when the app initially opens up.
I've narrowed this down to the fact that in these cases mReactInstanceManager.getCurrentReactContext() is null...for some reason.
Here's my code from MainActivity.java:
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onPause();
//send the appState back to JS
Log.d("REACT_STATE", "Paused"); //this always fires
if(mReactInstanceManager.getCurrentReactContext()!=null) {
WritableMap params = Arguments.createMap();
params.putString("currentAppState", "background");
sendEvent(mReactInstanceManager.getCurrentReactContext(), "appStateChange", params);
}
}
}
and,
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onResume(this, this);
//send the appState back to JS
Log.d("REACT_STATE", "Resumed"); //this also always fires
if(mReactInstanceManager.getCurrentReactContext()!=null) {
WritableMap params = Arguments.createMap();
params.putString("currentAppState", "foreground");
sendEvent(mReactInstanceManager.getCurrentReactContext(), "appStateChange", params);
}
}
}
and this is the emitter code:
private void sendEvent(ReactContext reactContext,
String eventName,
@Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
The JS side of things is set up OK and working - I can provide this code if it helps. I'm fairly certain my issue lies on this side. Am I trying to emit this at the wrong time? Do I need to move it elsewhere? Any advice is much appreciated!