如何在 React Native 中收听 App 启动和关闭?

jun*_*lin 5 android ios react-native

当应用程序启动和关闭时,我需要跟踪一些日志事件(仅一次)。

首先我在Homescreen 中执行此操作componentDiMount(),但在某些情况下它会被实例化多次,从而导致重复启动事件日志。

==============编辑================

AppState只能监听背景活动事件。

在 Android 上关闭应用程序时(按返回键或在最近应用程序菜单中关闭),它实际上回到了后台。重新打开应用程序时,它会将应用程序从后台恢复为活动状态。这与在后台活动(不关闭)之间切换应用程序相同

所以我无法确定它是首次启动还是 使用切换应用程序状态AppState

min*_*ist 2

注意:以下答案是在 OP 未编辑问题以添加有关 AppState 限制的信息时编写的。

使用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() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}
Run Code Online (Sandbox Code Playgroud)