1

I have a problem when react native app goes to background or foreground. I am trying to call my action in a set interval when app in background or foreground but unable to find any solution.

In my app when user click on start navigation button and it redirect user to the Default map application of phone. I need to update my Database in a time interval when app not active.

I have used Appstate to check when app is not active. And set setInterval function to call action in a set of time interval.

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._interval = setInterval( () => {
      console.log('check');
    }, 5000);

      if(global.routeName && global.routeName != '' && global.routeName == "OrderDetail"){
        this.props.navigation.navigate("OrderDetail",{orderId: global.orderId});
      }
    }else{
this._interval = setInterval( () => {
      console.log('check 2');
    }, 5000);
}
    this.setState({appState: nextAppState});
  };

I expected when app goes to background or foreground setInterval should be call in a set of interval, but the actual i'm unable to get my output.

himanshu
  • 461
  • 9
  • 21

2 Answers2

3

when app is in background "setInterval" will not work . You can use react-native-background-timer

Sample code example

BackgroundTimer.runBackgroundTimer(() => { 
//code that will be called every 3 seconds 
}, 
3000);
//rest of code will be performing for iOS on background too

BackgroundTimer.stopBackgroundTimer(); //after this call all code on background stop run.
Mehran Khan
  • 3,616
  • 1
  • 13
  • 10
0

You can listen to the appState event. From here

import React, {Component} from 'react'
import {AppState, Text} from 'react-native'

class AppStateExample 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});
  }

  render() {
    return (
      <Text>Current state is: {this.state.appState}</Text>
    );
  }

}

By the way, this will always say 'Current state is: active', because that is the only state in which the app will be visible for the user

Rishav Kumar
  • 4,979
  • 1
  • 17
  • 32