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
In React Native, performing a task in the background might seem daunting at first. It is not as simple as writing a function in JavaScript, where the function is executed even after the activity is killed. Instead, React Native uses Headless JS to execute JavaScript code in the background.
With @react-native-community/hooks you can use the useAppState hook to check the app state. When you close the app, it gets a state of unknown once you open it back. When is in background, it says background' or 'inactive'.
Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.
React Native AppState helps you to know the currents state of the application. It will give you the information that the application is in the foreground or in the background, and will notify you on the change of state.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With