0

I want an event when the user closes the app from the background. For example, when I press the left button on a Galaxy S7 I am seeing all apps which are in the background. When I swipe the app to the left I destroy the app. Is it possible to call an event when this happens? I think in android lifecycle that is the event onDestroy ()

otto
  • 1,815
  • 7
  • 37
  • 63
  • This question is similar to this https://stackoverflow.com/questions/38962034/how-to-detect-when-a-react-native-app-is-closed-not-suspended could you please take a look to confirm that is what you need to do? – ricardoorellana May 15 '18 at 21:50
  • no this is when somebody close the app. I mean when the app get destroyed. – otto May 15 '18 at 21:59

2 Answers2

3

Android have onDestroy lifecycle event

If you want to listen this event on JS, you need to write this function in mainActivity.

Write this function in the MainActivity class:

  private static final String TAG = "MainActivity";

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

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

        }
    Log.i(TAG, "onDestroy: ");
}

Then listen listen event in useEffect:

  useEffect(() => {
DeviceEventEmitter.addListener('ActivityStateChange', e => {
  console.log('onDestroy')
});

return () => DeviceEventEmitter.removeAllListeners();
}, []);

Also if you want inactive event cases on android, take a look at it https://stackoverflow.com/a/41009169/13890802

0

You might use React Native Modules to listen to the activity lifecycle onDestroy. You would have to create your own native module.

A native module is a Java class that usually extends the ReactContextBaseJavaModule class and implements the functionality required by the JavaScript.

Abhishek Thapliyal
  • 3,497
  • 6
  • 30
  • 69
ricardoorellana
  • 2,270
  • 21
  • 35