react native: 两次点击返回退出APP或者监听app后台/前台切换

import React from 'react';
import {
     View, AppState, ToastAndroid, BackHandler} from 'react-native';

class HomeScreen extends React.Component {
     

    constructor(props) {
     
        super(props);

        this.state = {
     
            appState: AppState.currentState,
        };
    }


    componentDidMount = () => {
      
        //监听 : app从后台进入前台,或者从前台进入了后台
        AppState.addEventListener('change', this._handleAppStateChange);
        //监听 : 两次点击返回按钮退出APP
        if (Platform.OS === 'android') {
     
            BackHandler.addEventListener('hardwareBackPress', this._onBackAndroid);
        }
    };

    componentWillUnmount() {
     
        AppState.removeEventListener('change', this._handleAppStateChange);
        if (Platform.OS === 'android') {
     
            BackHandler.removeEventListener('hardwareBackPress', this._onBackAndroid);
        }
    }

    _onBackAndroid = () => {
     
        //判断   该页面是否处于聚焦状态
        if (this.props.navigation.isFocused()) {
     
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
     
                //最近2秒内按过back键,可以退出应用。
                BackHandler.exitApp();//直接退出APP
                return false;
            } else {
     
                this.lastBackPressed = Date.now();
                ToastAndroid.show('再按一次退出应用', 1000);//提示
                return true;
            }
        }

    };


    _handleAppStateChange = (nextAppState) => {
     
        console.log('nextAppState == ', nextAppState);
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
     
            console.log('App has come to the foreground!');
        }
        this.setState({
     appState: nextAppState});
    };


	//.............
}


appState :

  • active - 应用正在前台运行
  • background - 应用正在后台运行。用户既可能在别的应用中,也可能在桌面。
  • inactive - 这是一个过渡状态,不会在正常的React Native应用中出现

你可能感兴趣的:(react native: 两次点击返回退出APP或者监听app后台/前台切换)