Friday, August 16, 2019

React Native Detect App is in Background or Foreground using AppState

This tutorial explains how to detect app is in foreground or background  using AppState component in react native application. In both android & iOS mobile devices the applications runs on 2 modes :
1. First mode is Foreground known as front active mode on which the application remains open on mobile screen.
2. Second mode is Background mode in which the app is in background and user is accessing other apps on that time.

The AppState component in react native is used to notify the user whether the app is in background or foreground and returns a string.

React Native Detect App is in Background or Foreground using AppState

App States

active - The app is running in the foreground
background - The app is running in the background. The user is either:
  • in another app
  • on the home screen
  • [Android] on another Activity (even if it was launched by your app)
[iOS] inactive - This is a state that occurs when transitioning between foreground & background, and during periods of inactivity such as entering the Multitasking view or in the event of an incoming call

For more information, see Apple's documentation

Detect App is in Background or Foreground using AppState in React Native

Lets see the complete source code that helps to detect app is in foreground or background  using AppState component in react native application.

Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 3: Through react , react-native packages import all required components.
import React, { Component } from 'react';
import { StyleSheet, View, Platform, AppState, Text  } from 'react-native';

Step 4: Lets create constructor block inside your App component. In the constructor block we have created state variables named as appState. This state variable store current state of an application.
 constructor() {
    super();
    this.state = {
      appState: AppState.currentState,
    }
  }

Step 5: Create the componentDidMount()  & componentWillUnmount() method inside the App component. This will automatically called, when app goes foreground or background state.
componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

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

Step 6: Create a function named as _handleAppStateChange(). This will check the current state of mobile application.

App States values definition:

  • active : The application is running in active foreground mode.
  • background: The application is in background mode or minimize.
  • inactive: The application is in inactive mode. This mode occurs when transitioning between foreground and background mode.

_handleAppStateChange = (nextAppState) => {

    this.setState({ appState: nextAppState });

    if (nextAppState === 'background') {
      // Do something here on app background.
      console.log("App is in Background Mode.")
    }

    if (nextAppState === 'active') {
      // Do something here on app active foreground mode.
      console.log("App is in Active Foreground Mode.")
    }

    if (nextAppState === 'inactive') {
      // Do something here on app inactive mode.
      console.log("App is in inactive Mode.")
    }
  };

Step 7: Implement render method inside the App class and wrapped the below layout design inside the root View component.  
render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={styles.headerText}>Current state is: {this.state.appState}</Text>
      </View>
    );
  }

Step 8 : Apply the below style sheet design. 
const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: (Platform.OS == 'ios') ? 20 : 0,
    margin: 10
  },
   headerText: {
    fontSize: 20,
    margin: 10,
    fontWeight: "bold"
  },
});

Step 9: The below screen of Command prompt window after executing react-native log-android command and check the current status of the application after minimize and maximize the application
react-native log-android 


Complete Source Code for App.js 

Lets see the complete source code that helps to detect app is in foreground or background  using AppState component in react native application.

import React, { Component } from 'react';
import { StyleSheet, View, Platform, AppState, Text  } from 'react-native';

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 = (nextAppState) => {

    this.setState({ appState: nextAppState });

    if (nextAppState === 'background') {
      // Do something here on app background.
      console.log("App is in Background Mode.")
    }

    if (nextAppState === 'active') {
      // Do something here on app active foreground mode.
      console.log("App is in Active Foreground Mode.")
    }

    if (nextAppState === 'inactive') {
      // Do something here on app inactive mode.
      console.log("App is in inactive Mode.")
    }
  };


  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={styles.headerText}>Current state is: {this.state.appState}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: (Platform.OS == 'ios') ? 20 : 0,
    margin: 10
  },
   headerText: {
    fontSize: 20,
    margin: 10,
    fontWeight: "bold"
  },
});

Screenshot :

react-native-detect-app-is-in-foreground-background
This is all about React Native Detect App is in Background or Foreground using AppState. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment