历览千载书,时时见遗烈。这篇文章主要讲述ReactNative: 使用AppState的API获取App的状态相关的知识,希望能为你提供帮助。
一、简介
App在运行的整个过程中,它会有不同的运行状态,例如激活失活状态、前后台进入和离开状态等。开发者可以根据App的不同状态选择合适的时机完成需要的工作。ReactNative中提供了AppState这个API来告知App的状态,它还可以通知状态的改变、甚至用于消息通知的推送等。
二、API
AppState提供了一个属性来获取当前App的状态。
//App的当前状态 AppState.currentState
AppState提供了两个静态方法分别用来添加和移除事件监听
//添加事件监听 //type: 事件的类型,如状态改变:change、内存警告:memoryWarning //handler:监听的回调 AppState.addEventListener( type: string, handler: Function)//移除事件监听 //type: 事件的类型,如状态状态:change、内存警告:memoryWarning //handler:监听的回调 AppState.removeEventListener( type: string, handler: Function)
三、使用
现在就来使用提供的API进行一下简单的测试,示例如下:
index.ios.js
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */import React, { Component } from ‘react‘; import { AppRegistry, StyleSheet, View, Text, AppState } from ‘react-native‘; export default class ReactNativeDemo 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}); console.log(‘nextAppState-----‘,nextAppState); }; constructor(){ super(); const currentState = AppState.currentState; console.log(‘currentState-----‘,currentState); }render() { return ( < View style={[styles.flex,styles.bgColor,styles.center]}> < Text> Current state is: {this.state.appState}< /Text> < /View> ); } }const styles = StyleSheet.create({ flex: { flex: 1 }, bgColor: { backgroundColor: ‘#1FB9FF‘ }, center: { alignItems: ‘center‘, justifyContent: ‘center‘ } }); AppRegistry.registerComponent(‘ReactNativeDemo‘, () => ReactNativeDemo);
xcode日志如下:【期间将app进入后台和进入前台过】
2019-12-31 11:47:08.472 [info][tid:com.facebook.react.javascript] ‘currentState-----‘, ‘active‘ 2019-12-31 11:47:11.310 [info][tid:com.facebook.react.javaScript] ‘nextAppState-----‘, ‘inactive‘ 2019-12-31 11:47:11.907 [info][tid:com.facebook.react.JavaScript] ‘nextAppState-----‘, ‘background‘ 2019-12-31 11:47:15.231 [info][tid:com.facebook.react.JavaScript] App has come to the foreground! 2019-12-31 11:47:15.244 [info][tid:com.facebook.react.JavaScript] ‘nextAppState-----‘, ‘active‘
【ReactNative: 使用AppState的API获取App的状态】
推荐阅读
- uni-app:如何绑定新字段在已有的列表中
- uni appuni ui的引入和调用
- Appium+Pytest实现app并发测试
- @SpringBootApplication的说明
- webapp开发之IIS进程调试
- AndroidStudio报错(GradleSyncIssues-Could not install Gradle distribution from...)
- 基于WebRtc实现安卓视频一对一聊天
- AndroidStudio更新时报错(Connection Error,Temp directory inside installation)
- 百度DMA+小度App的蓝牙语音解决方案技术难点解析