React Native Detect App is in Background or Foreground using AppState

In both android & iOS mobile devices the applications runs on 2 modes. First mode is Foreground known as front active mode on which the application remains open on mobile screen. 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. So in this tutorial we would Detect App is in Background or Foreground using AppState in react native android iOS application.

Contents in this project Detect App is in Background or Foreground using AppState in React Native Android iOS App:

1. Import StyleSheet, Text, View & AppState component in your project’s App.js file.

2. Create constructor() function in your project’s class and make a State named as appState. We would assign the AppState.currentState object to appState state.

3. Create componentDidMount() inbuilt function in your main class & call the AppState.addEventListener() function here. We would call the _handleAppStateChange() function here. This method would call when app starts or app comes in foreground mode.

4. Creating componentWillUnmount() inbuilt method. Now we would call the AppState.removeEventListener() function here. This method will calls when app goes to background mode.

5. Create _handleAppStateChange() function with nextAppState parameter. This is our main function in this project. In this function we would check the appState value.

App States values definition:

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

6. Create a Text component in render’s return block and show the State value.

7. Creating Style.

8. Complete source code for App.js file class.

Screenshots:


The below screen of Command prompt window after executing
reactnative logandroid command.
Detect App is in Background