AppState
AppState
可以告诉你应用程序是在前台还是在后台,并在状态改变时通知你。
处理推送通知时,AppState经常用于确定意图和适当的行为。
App States
-
active
- 该应用程序在前台运行
-
background
- 该应用程序正在后台运行。用户要么在另一个应用程序中,要么在主屏幕上
-
inactive
- 这是在前景和背景之间转换时以及在处于非活动状态期间发生的状态,例如进入多任务处理视图或来电时
有关更多信息,请参阅 Apple的文档
基本用法
要查看当前状态,可以检查
AppState.currentState
哪些状态将保持最新状态。但是,
currentState
启动时将为空,
AppState
并通过网桥进行检索。
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() {