Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a react native app goes to background?

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

like image 378
Javier Manzano Avatar asked Oct 10 '17 08:10

Javier Manzano


People also ask

Can React Native apps run in the background?

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.

How do you know app is closed in React Native?

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'.

Where is background in React Native?

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.

What is AppState in React Native?

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.


1 Answers

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.

like image 194
Fortega Avatar answered Oct 19 '22 15:10

Fortega