How to detect when a React Native app is closed (not suspended)?

后端 未结 2 624
Happy的楠姐
Happy的楠姐 2020-12-02 09:58

I have looked everywhere and cannot find an answer to this. How can I detect when a user is trying to close my React Native app (as in the process is running, and they manua

2条回答
  •  既然无缘
    2020-12-02 10:32

    Looks like you can detect the previous state and compare it to the next state. You can't detect that the app is closing vs going into the background, from what I can find online, but you can detect if it was inactive (closed), or in the background.

    Example from React Native Docs

    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 (
          Current state is: {this.state.appState}
        );
      }
    
    }
    

提交回复
热议问题