美文网首页
RN-AppState

RN-AppState

作者: hliccy | 来源:发表于2017-07-14 20:00 被阅读144次

    ReactNative 提供了AppState 来告知 App当前状态:前台运行中、后台台运行中

    1 获取当前应用状态

    AppState.currentState

    * active 前台运行中
    * background 后台运行中
    * inactive  运行的过渡状态
    

    2 代码示例

    /**
     * Created by licc on 2017/7/9.
     */
    
    import React, {Component } from 'react';
    import {
        StyleSheet,
        View,
        Text,
        AppState
    } from 'react-native';
    
    import NavigationBar from './NavigationBar'
    
    
    export default class AppStateExample extends Component {
    
        componentWillMount(){
    
            //监听状态改变
            AppState.addEventListener('change', this.changeState);
    
            //监听内存报警
            AppState.addEventListener('memoryWarning', ()=>{console.log('内存报警....')});
        }
    
        componentWillUnmount(){
            AppState.removeEventListener('change', this.changeState());
        }
    
        changeState(state){
            alert('当前状态:'+state);
        }
    
        render() {
            return (
                <View style={styles.container}>
                    <NavigationBar
                        title={'AlertIOS'}
                        statusBar={{backgroundColor:'blue'}}
                    />
                    <Text style={styles.item}>监听中...</Text>
                </View>
            );
        }
    }
    
    const styles = StyleSheet.create({
    
        container:{
            flex:1
        },
    
        item:{
            marginTop:10,
            marginLeft:5,
            marginRight:5,
            height:30,
            borderWidth:1,
            padding:6,
            borderColor:'#ddd',
            textAlign:'center'
        },
    });
    
    

    相关文章

      网友评论

          本文标题:RN-AppState

          本文链接:https://www.haomeiwen.com/subject/qbmohxtx.html