调查FB(Facebook) 中的 AppState API https://facebook.github.io/react-native/docs/appstate.html
它在 FB 上有 3 个状态,总共 5 个状态。我在 FB 中只看到 3 个,但其他 2 个可能受支持,也可能不支持。
Active
- 该应用程序正在前台运行
background
- 该应用程序正在后台运行。用户要么在另一个应用程序中,要么在主屏幕上。
inactive
- 这是在前台和后台之间转换时以及在不活动期间(例如进入多任务视图或有来电时)发生的状态
看看苹果Docs https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html有关这些的更多信息。
您必须测试当手机处于锁定屏幕时会进入什么状态。我无法告诉你要使用什么状态,因为我从未测试过 api。
正如您从下面的代码中看到的,测试是在条件语句中完成的
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active')
我在这里以 facebook 为例,但附上change
事件监听器在componentDidMount
并删除在ComponentWillUnmount
并且代码将根据状态运行。
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>
);
}
}