欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ReactNative 退出到后台一定时间之后,跳转到登录界面

程序员文章站 2024-01-16 20:32:04
...
****实现长时间不操作应用,可以自定义多长时间,直接跳转到登录界面,登录之后才能再进行操作****
let pTimes;
let BACK_TO_LOGIN_TIME = 120;
constructor(props) {
   super(props);
   this.state={
       currentAppState:AppState.currentState,
   }
}

componentDidMount() {
    AppState.addEventListener('change', this.handleAppStateChange);
    pTimes =-1;
}

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

handleAppStateChange = (nextAppState) => {
    if (this.state.currentAppState.match(/inactive|background/) && nextAppState === 'active') {
        let tempTime = getCurrentTime();
        let waste = tempTime -pTimes;
        console.log('----'+preTimes+'----waste:' + waste)
        console.log('BACK_TO_LOGIN_TIME====='+BACK_TO_LOGIN_TIME)
        if (waste > BACK_TO_LOGIN_TIME) {
            InteractionManager.runAfterInteractions(()=>{
                this.props.navigator.resetTo({
                    component:Login,
                    name:'Login',
                })
            })
        toastShort('长时间未操作,需要重新登录')
        console.log('AppState:'+'It's too late,login again')
        }else{
            console.log('AppState:'+'回来的很及时')
        }
        console.log('AppState:'+'现在在前台')
    }else{
        //前台切换至后台
        console.log('AppState:'+'现在在后台')
        preTimes = getCurrentTime();
    }
    this.setState({ currentAppState:nextAppState});
    console.log('pTimes:'+pTimes);
}

//返回从1970年1月1日至今的毫秒数
export function getCurrentTime(){
    let date = new Date();
    return date.getTime();

}
相关标签: 监听应用状态