React Native Project to Detect Whether App is Running in Background or Foreground in Android or IOS

React Native Project to Detect Whether App is Running in Background or Foreground in Android or IOS

React Native Project to Detect Whether App is Running in Background or Foreground in Android or IOS

import React, {Component} from 'react';
import {AppState, StyleSheet, Text, View} from 'react-native';
 
class App extends Component {
  state = {
    appState: AppState.currentState,
  };
 
  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }
 
  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }
 
  _handleAppStateChange = (nextAppState) => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
    }
    this.setState({appState: nextAppState});
    console.log(nextAppState);
  };
 
  render() {
    return (
      <View style={styles.container}>
        <Text>Current state is: {this.state.appState}</Text>
      </View>
    );
  }
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
 
export default App;

import React, {useRef, useState, useEffect} from 'react';
import {AppState, StyleSheet, Text, View} from 'react-native';
 
const App = () => {
  const appState = useRef(AppState.currentState);
  const [appStateVisible, setAppStateVisible] = useState(appState.current);
 
  useEffect(() => {
    AppState.addEventListener('change', _handleAppStateChange);
 
    return () => {
      AppState.removeEventListener('change', _handleAppStateChange);
    };
  }, []);
 
  const _handleAppStateChange = (nextAppState) => {
    if (
      appState.current.match(/inactive|background/) &&
      nextAppState === 'active'
    ) {
      console.log('App has come to the foreground!');
    }
 
    appState.current = nextAppState;
    setAppStateVisible(appState.current);
    console.log('AppState', appState.current);
  };
 
  return (
    <View style={styles.container}>
      <Text>Current state is: {appStateVisible}</Text>
    </View>
  );
};
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});
 
export default App;

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment