当我在 React Native 中按下主屏幕按钮时如何调用函数
how can I call a funcation when I press home screen button in react native
我有一个声音播放器应用程序,我希望它在用户按下 android 中的主屏幕按钮时停止播放当前歌曲,实际上当按下主屏幕时声音正在播放。
我使用 componentWillUnmount
作为后退按钮,但对于主屏幕按钮我不知道应该使用什么?
您需要用户 AppState 来帮助您找到您的应用程序所处的状态。当 State 为 background
时,您可以执行您的逻辑
示例代码如下:
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
我有一个声音播放器应用程序,我希望它在用户按下 android 中的主屏幕按钮时停止播放当前歌曲,实际上当按下主屏幕时声音正在播放。
我使用 componentWillUnmount
作为后退按钮,但对于主屏幕按钮我不知道应该使用什么?
您需要用户 AppState 来帮助您找到您的应用程序所处的状态。当 State 为 background
时,您可以执行您的逻辑示例代码如下:
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