如何知道反应原生应用程序是否转到后台?

Jav*_*ano 15 javascript react-native

是否有可能知道RN应用程序是否已进入后台?任何回调或触发?

如果我听到componentDidUnmountcomponentWillUnmount正在播放的屏幕,只有当我回到另一个屏幕时才会被触发

谢谢

For*_*ega 20

你可以听听这个appState活动.来自https://facebook.github.io/react-native/docs/appstate.html:

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>
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 并非总是说“当前状态为:活跃” (2认同)

str*_*str 7

您可以使用AppState

应用状态

  • active - 应用程序在前台运行
  • background- 该应用程序正在后台运行。用户在另一个应用程序中或在主屏幕上
  • inactive - 这是在前台和后台之间转换时以及在进入多任务视图或有来电时等不活动期间发生的状态

  • 请注意,inactive 仅发生在 iOS 上 (7认同)