Search This Blog

Friday, June 18, 2021

React Native - Check Application is in Background or ForeGround with Time Diff - 10 seconds Move to Login Session Expired

 1. Install the below two mandatory npm plugins.

npm install --save react-native-async-storage

npm install --save moment


2. app.js


import React, { Component } from 'react';
import { StyleSheet, Text, View, AppState } from 'react-native';
//import Routing from "./src/routing/routing";
import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
//import { Actions } from 'react-native-router-flux';

export default class App extends Component {
constructor() {
super();
this.state = {
appState: AppState.currentState
}
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = async(nextAppState) => {
this.setState({ appState: nextAppState });
if (nextAppState === 'background') {
var previousTime = new Date();
await AsyncStorage.setItem( "previousTime", previousTime.toString() );
// Do something here on app background.
console.log( "App is in Background Mode @ ", previousTime );
}
if (nextAppState === 'active') {
// Do something here on app active foreground mode.
const start = moment( await AsyncStorage.getItem('previousTime') );
const end = moment();
//in original implementation, use minutes and check with N value.
//const range = end.diff(start,'minutes');
const range = end.diff(start,'seconds');
if ( range >= 10 ){
console.log ( "App is exit the Active Range, So moving to Login screen." );
/* Actions.login({"message":"Session Exit"} ); */
}
else{
console.log( "App is in Active Range, So continue your process ...");
}
}
if (nextAppState === 'inactive') {
// Do something here on app inactive mode.
console.log("App is in inactive Mode.")
}
};
render() {
return (
<View style={styles.MainContainer}>
{/* <Routing /> */}
<Text>Current state is: {this.state.appState}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
color: '#000'
}
});

No comments:

Hit Counter


View My Stats