当Android应用程序被暂时放到了后台,或者又重新回到前台,是否有相应的事件可以处理到?
例如,当你的应用暂时放到了后台,是否应该做出一些操作,暂时保存界面上的数据?
可以参考:
https://github.com/wix/react-native-navigation/issues/839
官方文档:
https://facebook.github.io/react-native/docs/appstate.html
官方示例代码:
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>
componentDidMount() {
console.log('componentDidMount================');
AppState.addEventListener('change', (state) => {
if (state === 'active') {
console.log('state active');
} else if (state === 'background') {
console.log('background');
} else if (state === 'inactive') {
console.log('inactive');
App States
active - 该应用程序在前台运行
background - 该应用程序正在后台运行。用户是:
在另一个应用中
在主屏幕上
[Android]在另一个Activity(即使它是由您的应用程序启动)
inactive - 这是在前景和背景之间转换时以及在处于非活动状态期间发生的状态,例如进入多任务处理视图或来电时