如何保持React Native像媒体播放器一样运行(可能是“前景”)?

时间:2019-07-10 14:27:31

标签: javascript android ios react-native

即使它在“前景”中,我如何保持React Native应用运行?我的意思是类似媒体播放器应用程序(Spotify,Netflix等)通常显示粘性通知的事情。 我需要该应用程序以继续收听外部事件(不一定是服务器),并且还需要不时不断地执行操作。 换句话说,我不希望操作系统杀死该应用程序,也不希望让用户知道这一点(如果用户知道,甚至更好)。

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用AppState中的React-native

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