如果我正在使用我的应用程序,然后使用主页按钮、应用程序切换器等将其关闭,有没有办法在检测到此事件时可靠地运行某些代码?我想做一些任务,例如取消计时器,安排通知等。
最佳答案
您可以使用 AppState
跟踪应用程序的状态由“ react 原生”提供
通过使用 AppState.currentState
您将知道应用程序是在前台、后台、事件还是非事件状态。如果你想在状态改变时执行一些任务,你可以使用 AppState
提供的事件监听器。 .
您可以在组件中添加以下逻辑来完成它 -
componentDidMount() {
AppState.addEventListener('change', this.handleStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleStateChange);
}
handleStateChange
每次应用程序从前台移动到后台时都会被调用,反之亦然,应用程序的当前状态作为参数传递。如需进一步引用,请参阅 docs
希望它有所帮助。
关于react-native - Expo.js : Capture event when my app goes into the background?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52269307/