如何检测 React Native 应用程序何时关闭(未挂起)? [英] How to detect when a React Native app is closed (not suspended)?

查看:41
本文介绍了如何检测 React Native 应用程序何时关闭(未挂起)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 manually manage their apps and force exit it). I would like to add logout functionality when this happens, however cannot find a way to detect it. AppState appears to only detect when the app is brought in and out of the background.

推荐答案

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

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.

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

}

这篇关于如何检测 React Native 应用程序何时关闭(未挂起)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆