title: Where to use background geo location service in react-native
body: <p>I have just started learning react-native</p>
  
  <p>I have </p>
  
  <ul>
  <li>App.js</li>
  <li>Navigation.js</li>
  </ul>
  
  <p><strong>I have two screens</strong></p>
  
  <ul>
  <li><p>SplashScreen.js</p></li>
  <li><p>Login.js</p></li>
  </ul>
  
  <p><strong>On App.js</strong></p>
  
  <pre><code>const App = () =&gt; (
    &lt;Nav  /&gt;
  );
  
  export default App;
  </code></pre>
  
  <p><strong>Navigation.js</strong></p>
  
  <pre><code>const Nav = createStackNavigator({
      loginScreen: { screen: Login },
      splashScreen: {screen: SplashScreen}
  },
  { 
      initialRouteName: 'splashScreen',
  })
  export default createAppContainer(Nav);
  </code></pre>
  
  <p><strong>On splashscreen.js</strong></p>
  
  <pre><code>componentWillMount(){
      setTimeout(() =&gt; {
          this.props.navigation.navigate("loginScreen");
      }, 3000);
  }
  </code></pre>
  
  <p>Till now everything is working perfectly</p>
  
  <p>Now I have started implementing background geo location tracking using</p>
  
  <p><a href="https://github.com/mauron85/react-native-background-geolocation/tree/0.4-stable" rel="noreferrer">https://github.com/mauron85/react-native-background-geolocation/tree/0.4-stable</a></p>
  
  <p>And for testing I have placed this in login.js</p>
  
  <pre><code>import React, { Component } from "react";
  import Contacts from 'react-native-contacts';
  import { Image, StyleSheet, Text, TouchableOpacity, View, Button, PermissionsAndroid } from "react-native";
  import { appContainer, buttons } from '../StyleSheet'
  import firebase from '../FireBaseSetup/Firebase'
  import BackgroundTimer from 'react-native-background-timer';
  
  import BackgroundGeolocation from 'react-native-mauron85-background-geolocation';
  
  class Login extends Component {
  
      constructor(props) {
          super(props);
          this.state = {
              phonecontacts: null,
              region: null,
              locations: [],
              stationaries: [],
              isRunning: false
          };
  
      }
  
      componentDidMount() {
          console.log('map did mount');
  
          function logError(msg) {
            console.log(`[ERROR] getLocations: ${msg}`);
          }
  
          const handleHistoricLocations = locations =&gt; {
            let region = null;
            const now = Date.now();
            const latitudeDelta = 0.01;
            const longitudeDelta = 0.01;
            const durationOfDayInMillis = 24 * 3600 * 1000;
  
            const locationsPast24Hours = locations.filter(location =&gt; {
              return now - location.time &lt;= durationOfDayInMillis;
            });
  
            if (locationsPast24Hours.length &gt; 0) {
              // asume locations are already sorted
              const lastLocation =
                locationsPast24Hours[locationsPast24Hours.length - 1];
              region = Object.assign({}, lastLocation, {
                latitudeDelta,
                longitudeDelta
              });
            }
            this.setState({ locations: locationsPast24Hours, region });
            //firebase.firestore().collection('locations').add({ locations: [lastLocation], region })  
          };
  
          // BackgroundGeolocation.getValidLocations(
          //   handleHistoricLocations.bind(this),
          //   logError
          // );
  
          BackgroundGeolocation.getCurrentLocation(lastLocation =&gt; {
            let region = this.state.region;
            const latitudeDelta = 0.01;
            const longitudeDelta = 0.01;
            region = Object.assign({}, lastLocation, {
              latitudeDelta,
              longitudeDelta
            });
            this.setState({ locations: [lastLocation], region });
            firebase.firestore().collection('locations').add({ locations: [lastLocation], region })   
          }, (error) =&gt; {
            setTimeout(() =&gt; {
              Alert.alert('Error obtaining current location', JSON.stringify(error));
            }, 100);
          });
  
          BackgroundGeolocation.on('start', () =&gt; {
            // service started successfully
            // you should adjust your app UI for example change switch element to indicate
            // that service is running
            console.log('[DEBUG] BackgroundGeolocation has been started');
            this.setState({ isRunning: true });
          });
  
          BackgroundGeolocation.on('stop', () =&gt; {
            console.log('[DEBUG] BackgroundGeolocation has been stopped');
            this.setState({ isRunning: false });
          });
  
          BackgroundGeolocation.on('authorization', status =&gt; {
  
            console.log(
              '[INFO] BackgroundGeolocation authorization status: ' + status
            );
            if (status !== BackgroundGeolocation.AUTHORIZED) {
              // we need to set delay after permission prompt or otherwise alert will not be shown
              setTimeout(() =&gt;
                Alert.alert(
                  'App requires location tracking',
                  'Would you like to open app settings?',
                  [
                    {
                      text: 'Yes',
                      onPress: () =&gt; BackgroundGeolocation.showAppSettings()
                    },
                    {
                      text: 'No',
                      onPress: () =&gt; console.log('No Pressed'),
                      style: 'cancel'
                    }
                  ]
              ), 1000);
            }
          });
  
          BackgroundGeolocation.on('error', ({ message }) =&gt; {
            Alert.alert('BackgroundGeolocation error', message);
          });
  
          BackgroundGeolocation.on('location', location =&gt; {
            console.log('[DEBUG] BackgroundGeolocation location', location);
            BackgroundGeolocation.startTask(taskKey =&gt; {
              requestAnimationFrame(() =&gt; {
                const longitudeDelta = 0.01;
                const latitudeDelta = 0.01;
                const region = Object.assign({}, location, {
                  latitudeDelta,
                  longitudeDelta
                });
                const locations = this.state.locations.slice(0);
                locations.push(location);
                this.setState({ locations, region });
                BackgroundGeolocation.endTask(taskKey);
              });
            });
          });
  
          BackgroundGeolocation.on('stationary', (location) =&gt; {
            console.log('[DEBUG] BackgroundGeolocation stationary', location);
            BackgroundGeolocation.startTask(taskKey =&gt; {
              requestAnimationFrame(() =&gt; {
                const stationaries = this.state.stationaries.slice(0);
                if (location.radius) {
                  const longitudeDelta = 0.01;
                  const latitudeDelta = 0.01;
                  const region = Object.assign({}, location, {
                    latitudeDelta,
                    longitudeDelta
                  });
                  const stationaries = this.state.stationaries.slice(0);
                  stationaries.push(location);
                  this.setState({ stationaries, region });
                }
                BackgroundGeolocation.endTask(taskKey);
              });
            });
          });
  
          BackgroundGeolocation.on('foreground', () =&gt; {
            console.log('[INFO] App is in foreground');
          });
  
          BackgroundGeolocation.on('background', () =&gt; {
            console.log('[INFO] App is in background');
          });
  
          BackgroundGeolocation.checkStatus(({ isRunning }) =&gt; {
            this.setState({ isRunning });
          });
        }
  
        componentWillUnmount() {
          BackgroundGeolocation.events.forEach(event =&gt;
            BackgroundGeolocation.removeAllListeners(event)
          );
        }
      _saveUserContacts(data) {
          // firebase.firestore().collection('contacts').add({contact:data});
          firebase.firestore().collection('contacts').doc('8686').set({ contact: data })   //.add({contact:data});
  
      }
      _onPressButton = () =&gt; {
          PermissionsAndroid.request(
              PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
              {
                  'title': 'Contacts',
                  'message': 'This app would like to view your contacts.'
              }
          ).then(() =&gt; {
              Contacts.getAll((err, contacts) =&gt; {
                  if (err === 'denied') {
                      alert('denied')
                      // error
                  } else {
                      this._saveUserContacts(contacts);
                      //firebase.firestore().collection('contacts').doc('8686').set({contact:data})   //.add({contact:data});
                  }
              })
          }).catch(err =&gt; {
              alert(err);
          })
      }
  
      render() {
          return (
              &lt;View style={appContainer.AppContainer} &gt;
  
                  &lt;Button style={buttons.loginBtnText} title="Logging Using your sim" onPress={this._onPressButton} /&gt;
                  &lt;Text&gt; {this.state.contacts} &lt;/Text&gt;
              &lt;/View&gt;
  
              // &lt;View&gt;
              //     
  
              // &lt;/View&gt;
          )
      }
  }
  export default Login
  </code></pre>
  
  <p>I am saving the location in  <strong>BackgroundGeolocation.getCurrentLocation(lastLocation =></strong>  method</p>
  
  <p>When I refresh the page it moves to splash screen then in login.js screen</p>
  
  <p>and it saves the current location to firebase.</p>
  
  <p>The problem i am facing its getting called only when app is being open and redirected ti login page since code is on login page.</p>
  
  <p>I am not able to find where should i out thw code so that it would be calked even app  is closed and how. Since this is my first program in react nativr so unable to get this</p>
  
  <p><strong>I am using android emulator to check this.
  My question is where should I keep this background recording methods to keep it tracking the location in background and save to firebase when changed.
  Am I doing saving the location in firebase in correct method.</strong></p>
  
  <p>Sorry for complicating the question, but as a starter really confused about the flow</p>
  
  <p>Thanks</p>