首页 > 解决方案 > 当我按下主屏幕按钮反应原生时如何调用函数

问题描述

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

我使用componentWillUnmount后退按钮,但对于主屏幕按钮我不知道应该使用什么?

标签: reactjsfunctionreact-nativeaudionative

解决方案


您需要使用AppState来帮助您找到您的应用程序处于哪个状态。当 State 为背景时,您可以执行您的逻辑

这是示例代码:

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

推荐阅读