How to know if a react native app goes to background?
You can use the AppState
:
App States
active
- The app is running in the foregroundbackground
- The app is running in the background. The user is either in another app or on the home screeninactive
- This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call
You can listen to the appState
event.
From https://facebook.github.io/react-native/docs/appstate.html:
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}
By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user.