问题描述
我到处都是,找不到答案.如何检测用户何时试图关闭我的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应用何时关闭(未暂停)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!