javascript 如何知道 React Native 应用程序是否进入后台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46662004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 06:51:15  来源:igfitidea点击:

How to know if a react native app goes to background?

javascriptreact-native

提问by Javier Manzano

Is it possible to know if a RN app has gone to background? Any callback or trigger?

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

If I listen to componentDidUnmountor componentWillUnmountof the screen I'm on, it will only be fired if I go back/forth to another screen

如果我收听componentDidUnmountcomponentWillUnmount播放我所在的屏幕,它只会在我来回/前进到另一个屏幕时被触发

回答by Fortega

You can listen to the appStateevent. From https://facebook.github.io/react-native/docs/appstate.html:

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

}

By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user.

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

回答by str

You can use the AppState:

您可以使用AppState

App States

  • active- The app is running in the foreground
  • background- The app is running in the background. The user is either in another app or on the home screen
  • inactive- This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call

应用状态

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