Anyone who is still wondering, onWindowFocusChanged method can help with that task, it handles events when a user moves to Recents screen and opens Notification center, and comes back to a foreground respectively.
Copy that code into your MainActivity.java.
@Override
public void onWindowFocusChanged(boolean hasFocus) {
ReactContext reactContext = getReactInstanceManager()
.getCurrentReactContext();
WritableMap params = Arguments.createMap();
if (hasFocus) {
params.putString("event", "active");
} else {
params.putString("event", "inactive");
}
if (reactContext != null) {
getReactInstanceManager()
.getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("ActivityStateChange", params);
}
}
Don't forget to have that stuff imported as well:
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
After that React Native code:
useEffect(() => {
const nativeEventListener = DeviceEventEmitter.addListener(
'ActivityStateChange',
e => {
console.log(e.event)
},
);
return () => {
DeviceEventEmitter.removeAllListeners();
}
}, []);
UPD:
It's better to use NativeEventEmitter on RN side:
const NativeEvent = new NativeEventEmitter();
useEffect(() => {
const handleActiveState = NativeEvent.addListener('ActivityStateChange', (e) => {
console.log(e.event);
});
return () => {
handleActiveState.remove();
}
}, []);