tolliced
tolliced

Reputation: 53

Expo.js: Capture event when my app goes into the background?

If I'm using my app and then switch out of it using the home button, app switcher, etc, Is there a way to reliably run some code when this event is detected? I want to do some tasks such as cancelling timers, scheduling notifications, and so on.

Upvotes: 5

Views: 3862

Answers (1)

AKAP
AKAP

Reputation: 526

You can track app's state using AppState provided by 'react-native'

By using AppState.currentState you will know whether the app is in foreground, background, active or inactive. If you want to perform some tasks whenever the state changes you can use event listeners provided by AppState.

You can add the following logic in your Component to get it done -

componentDidMount() {
  AppState.addEventListener('change', this.handleStateChange);
}

componentWillUnmount() {
  AppState.removeEventListener('change', this.handleStateChange);
}

handleStateChange will be called every time the app moves from foreground to background or vice-versa with the app's current state passed as an argument.

For further reference see the docs

Hope it helped.

Upvotes: 7

Related Questions