当我在本机反应中按下主屏幕按钮时,如何调用功能

时间:2018-12-26 06:44:54

标签: reactjs function react-native audio native

我有一个声音播放器应用程序,我希望它在用户按下android中的主屏幕按钮时停止播放当前歌曲,而实际上在按下主屏幕时正在播放声音。

我将componentWillUnmount用于后退按钮,但对于主屏幕按钮却不知道该怎么用?

1 个答案:

答案 0 :(得分:1)

您需要使用 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>
    );
  }

}

应用状态

active - The app is running in the foreground

background - The app is running in the background. The user is either:
in another app
on the home screen
[Android] on another Activity (even if it was launched by your app)

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