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

新手上路,请多包涵

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

原文由 Dale_Plante 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 585
1 个回答

看起来您可以检测到以前的状态并将其与下一个状态进行比较。从我可以在网上找到的内容中,您无法检测到应用程序正在关闭与进入后台,但您可以检测到它是 inactive (关闭),还是在 background

React Native 文档 中的示例

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>
    );
  }

}

原文由 user888750 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题