React-NativeReact Native学习React-Native开发进阶

007-React-Native的AppState

2017-06-26  本文已影响439人  Time_情书

欢迎各位同学加入群:397885169,里面大神超多,会帮助解决各种问题。

一:
有一个特殊需求:当应用运行时,进入后台,当在次打开应用时,需要进行相关判断。判断用户在后台的时间。在实现过程中,遇到很多坑,其中,使用定时器是一个最简单的思路,setTimeout,但是,coding的过程中,发现,进入后台时,定时器数据会错乱,导致系统定时错误,并且不能clearTimeout。则,换了另一种思路,判断两次的时间。

二:Coding

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    AppState,
    ToastAndroid
} from 'react-native';
var backgroundTimes ='';
export default class  App extends Component {
    constructor(props){
        super(props);
        this._handleAppStateChange = this.handleAppStateChange.bind(this);
        this.state = {
            _appState:AppState.currentState,
        };
    }
    componentWillMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);

    }
    handleAppStateChange(appState) {
        if (appState==='background'){
            backgroundTimes=new Date().getTime();
        }
        else{
            if(backgroundtimes!=''){
                var activeTimes=new Date().getTime();
                var sjc = activeTimes - backgroundTimes;
               if(sjc>5000){
                   alert('已经超时........')
               }
            }
        }
    }
    render() {
        return (
            <View style={styles.container}>
                <Text>当前App状态信息如下:</Text>
                <Text>
                    {this.state._appState}
                </Text>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
});
上一篇 下一篇

猜你喜欢

热点阅读