首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

AppState

AppState 可以告诉你应用程序是在前台还是在后台,并在状态改变时通知你。

处理推送通知时,AppState经常用于确定意图和适当的行为。

App States

  • active - 该应用程序在前台运行
  • background - 该应用程序正在后台运行。用户要么在另一个应用程序中,要么在主屏幕上
  • inactive - 这是在前景和背景之间转换时以及在处于非活动状态期间发生的状态,例如进入多任务处理视图或来电时

有关更多信息,请参阅Apple的文档

基本用法

要查看当前状态,可以检查AppState.currentState哪些状态将保持最新状态。但是,currentState启动时将为空,AppState并通过网桥进行检索。

代码语言:javascript
复制
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>
    );
  }

}

这个例子只会显示“当前状态为:活动状态”,因为应用程序仅在处于active状态时才对用户可见,并且空状态只会暂时发生。

方法

=(;, ()

addEventListener(type, handler)

通过监听change事件类型并提供处理程序,为AppState更改添加处理程序

TODO:现在是届时AppState的NativeEventEmitter一个子类,我们可以弃用addEventListener,并removeEventListener与只使用addListenerlistener.remove()直接。尽管如此,这将是一个突破性的变化,因为方法和事件名称都不相同(addListener事件当前需要全局唯一)。

removeEventListener(type, handler)

通过传递change事件类型和处理程序来移除处理程序

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com