如何检测React Native应用程序何时关闭(未暂停)?

Dal*_*nte 44 mobile reactjs react-native

我到处寻找,找不到答案.如何检测用户何时尝试关闭我的React Native应用程序(如在进程正在运行,并且他们手动管理他们的应用程序并强制退出它).我希望在发生这种情况时添加注销功能,但无法找到检测它的方法.AppState似乎只检测应用程序何时进入和退出后台.

小智 20

看起来您可以检测到先前的状态并将其与下一个状态进行比较.你无法检测到应用程序正在关闭而不是进入后台,我可以在网上找到它,但你可以检测它是否inactive(关闭),或者在background.

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

}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回复,但遗憾的是,这可以检测应用程序何时处于后台或前置,而不是关闭 (16认同)
  • 这根本无法回答问题。您可以完成此操作,只需使用第3方库即可。请查看react-native-queue了解更多信息:https://github.com/billmalarky/react-native-queue#os-background-task-full-example (3认同)
  • 非活动状态仅适用于 iOS。在此处检查每个平台的所有可用状态:https://reactnative.dev/docs/appstate (2认同)