ReactNative: 使用AppState的API获取App的状态

时间:2022-06-14 05:52:03

一、简介

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