Is it possible to know if a RN app has gone to background? Any callback or trigger?
If I listen to componentDidUnmount
or componentWillUnmount
of the screen I'm on, it will only be fired if I go back/forth to another screen
Is it possible to know if a RN app has gone to background? Any callback or trigger?
If I listen to componentDidUnmount
or componentWillUnmount
of the screen I'm on, it will only be fired if I go back/forth to another screen
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.