相关文章推荐
害羞的滑板  ·  BCI - Better Cotton ...·  1 月前    · 
礼貌的海龟  ·  匈牙利语- 知乎·  2 年前    · 

React-Native - 使用AppState获取App运行状态(以及监听状态改变事件)

有时我们需要知道应用当前的运行状态,这样我们可以根据不同的状态进行相应的操作。React Native 提供了 AppState 来告知我们 App 当前的状态:激活(前台运行中)、还是后台运行。甚至可以通知我们状态的改变。下面分别对这两种情况进行介绍。


1,主动获取当前应用状态

我们可以使用 AppState.currentState 来获取应用的状态,返回值如下:

active:前台运行中

background:后台运行中

inactive:运行的过渡状态


(1)效果图

点击按钮后,将当前状态显示出来。

  • (2)样例代码

import React, { Component } from 'react';

import {

AppRegistry,

StyleSheet,

Text,

View,

AppState

} from 'react-native';

//默认应用的容器组件

class App extends Component {

render() {

return (

<View style={styles.container}>

<Text style={styles.item} onPress={this.getCurrentState.bind(this)}>

获取当前状态

</Text>

</View>

);

}

//获取当前状态

getCurrentState() {

alert("当前状态:" + AppState.currentState)

}

}

//样式定义

const styles = StyleSheet.create({

container:{

flex: 1,

marginTop:25

},

item:{

marginTop:10,

marginLeft:5,

marginRight:5,

height:30,

borderWidth:1,

padding:6,

borderColor:'#ddd',

textAlign:'center'

},

});

AppRegistry.registerComponent('HelloWorld', () => App);

2,监听状态的变化

我们可以在代码中添加相关的事件监听:

AppState.addEventListener:用于添加事件监听

AppState.removeEventListener:用于删除事件监听


(1)效果图

程序启动后会自动监听状态改变事件、以及内存报警事件。按 home 键将 App 退到后台,接着再回到前台运行可以看到效果。

(2)样例代码

import React, { Component } from 'react';

import {

AppRegistry,

StyleSheet,

Text,

View,

AppState

} from 'react-native';

//默认应用的容器组件

class App extends Component {

componentWillMount() {

//监听状态改变事件

AppState.addEventListener('change', this.handleAppStateChange);

//监听内存报警事件

AppState.addEventListener('memoryWarning', function(){

console.log("内存报警....");

});

}

componentWillUnmount() {

//删除状态改变事件监听

AppState.removeEventListener('change', this.handleAppStateChange);

}

render() {

return (

<View style={styles.container}>

<Text style={styles.item}>监听中...</Text>

</View>

);

}

//状态改变响应

handleAppStateChange(appState) {

alert('当前状态为:'+appState);

}

}

//样式定义

const styles = StyleSheet.create({

container:{

flex: 1,

marginTop:25

},

item:{

marginTop:10,

marginLeft:5,

marginRight:5,

height:30,

borderWidth:1,

padding:6,

borderColor:'#ddd',

textAlign:'center'

},

});

AppRegistry.registerComponent('HelloWorld', () => App);

发布于 2019-02-15 10:21