Skip to content Skip to sidebar Skip to footer

React Native AppState Has No 'inactive' State On Android

I am trying to change the UI just before the user leaves the app (user is in multi-tasking view or switches to some other app). To be more specific when user leaves the app I want

Solution 1:

If you need to, you can simulate the same states as iOS by adding some code to MainActivity.java to listen to its lifecycle events

//onResume = 'active'  
//onPause = 'inactive'  
//onStop = 'background' 

@Override
public void onResume() {
    super.onResume();
    ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
    WritableMap params = Arguments.createMap();
    params.putString("event", "active");

    // when app starts reactContext will be null initially until bridge between Native and React Native is established
    if(reactContext != null) {
        getReactInstanceManager().getCurrentReactContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("ActivityStateChange", params);
    }
}

@Override
public void onPause() {
    super.onPause();
    ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
    WritableMap params = Arguments.createMap();
    params.putString("event", "inactive");

    if(reactContext != null) {
        getReactInstanceManager().getCurrentReactContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("ActivityStateChange", params);
    }
}

@Override
public void onStop() {
    super.onStop();
    ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
    WritableMap params = Arguments.createMap();
    params.putString("event", "background");

    if(reactContext != null) {
        getReactInstanceManager().getCurrentReactContext()
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit("ActivityStateChange", params);
    }
}

Then in your JS listen to these lifecycle changes using DeviceEventEmitter

const nativeEventListener = DeviceEventEmitter.addListener('ActivityStateChange',
  (e)=>{
      console.log(e.event);
})

Solution 2:

For android you can use 'background' instead of 'inactive' like this:

  AppState.addEventListener('change', state => {

  if ( state === 'background') {
    //write your code here
   }

});

Post a Comment for "React Native AppState Has No 'inactive' State On Android"