【问题标题】:How to know if a react native app goes to background?如何知道反应原生应用程序是否进入后台?
【发布时间】:2018-03-21 13:57:08
【问题描述】:

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

如果我收听当前屏幕的componentDidUnmountcomponentWillUnmount,则只有在我返回/返回另一个屏幕时才会触发

【问题讨论】:

标签: javascript react-native


【解决方案1】:

您可以收听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>
    );
  }

}

顺便说一句,这将始终显示“当前状态为:活动”,因为这是应用对用户可见的唯一状态。

【讨论】:

  • 那不是总是说'当前状态是:活动'
  • 请注意,如果您使用钩子,则此答案(以及 React Native 官方文档网站上的 AppState example)已过时。问题是事件侦听器只添加一次,因此它会拍摄当时任何状态的快照并且之后不会更新,即使事件侦听器被多次调用也是如此。有关详细讨论,请参阅this
  • iOS 应用程序从横向转到纵向,同时转到后台并再次转到前台,多亏了这种方法,现在我可以使用 react-native-orientation 切换回横向。
  • 这个答案显示了如何监听前景,而不是背景。可能会更清楚。
【解决方案2】:

您可以使用AppState:

应用状态

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

【讨论】:

  • 请注意,inactive 只发生在 iOS 上
【解决方案3】:

AppState.removeEventListener 似乎已被弃用,所以我这样做了:

import React from 'react'
import { AppState } from 'react-native'

class AppStateClassComponent extends React.PureComponent {

    constructor(props){
        super(props)

        this.state = {
            appState: ''
        }

        this.onAppStateChange = (nextAppState) => {
            if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
                console.log('App has come to the foreground!')
            }
            this.setState({ appState: nextAppState });
        }

        this.app_state = null
    }

    componentDidMount() {
        this.permission_check()
        if(this.app_state === null){
            this.app_state = AppState.addEventListener('change', this.onAppStateChange)
        }
    }

    componentWillUnmount() {
        if(this.app_state !== null){
            this.app_state?.remove()
            this.app_state = null
        }
    }

    render() {
        return (
            <Text>Current state is: {this.state.appState}</Text>
        )
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多