当我们的程序在前后台直接做切换时,有时需要一些必要的动作,如暂停背景音乐、保存用户输入等。在Android上,我们使用的是onPause和onResume,RN提供AppState来监听APP的状态,简略使用方法如下,具体的API文档参见AppState
import {
AppState,
} from 'react-native';
_handleAppStateChange(nextAppState) {
const { appState, backgroundMusic } = this.state;
if (appState.match(/inactive|background/) && nextAppState === 'active') {
if (backgroundMusic) {
backgroundMusic.play();
} else {
this._playBackgroundMusic();
}
} else if (appState === 'active' && nextAppState.match(/inactive|background/)) {
if (backgroundMusic) {
backgroundMusic.pause();
}
}
this.setState({appState: nextAppState});
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
网友评论