简体   繁体   中英

Background location tracking not working - Expo - Android

I am working on something where I need to track background location if the app is in background and also if the device is asleep. I currently have it working for app in background but it stops tracking when the device is asleep. I am using Expo for the app and using Expo Task Manager alongside Expo Location to fetch location in background. Anyone have any idea how to fetch location while app is in background and device is in sleep mode ?

Here's the code

import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';

const App = () => {
  useEffect(() => {
    (async () => await _askForLocationPermission())();
  });

  this.backgroundLocationFetch = async () => {
    const { status } = await Location.requestBackgroundPermissionsAsync();
    if (status === 'granted') {
      console.log('cmon dance with me!')
      await Location.startLocationUpdatesAsync('FetchLocationInBackground', {
        accuracy: Location.Accuracy.Balanced,
        timeInterval: 3000,
        distanceInterval: 1,
        foregroundService: {
          notificationTitle: 'Live Tracker',
          notificationBody: 'Live Tracker is on.'
        }
      });
    }
  }



  const _askForLocationPermission = async () => {
    (async () => {
      let { status } = await Location.requestBackgroundPermissionsAsync();
      if (status !== 'granted') {
        setgpsErrorMsg('Permission to access location was denied');
      }
    })();
  };


  return(
    <View>
      <Text></Text>
    </View>
  )
};

TaskManager.defineTask('FetchLocationInBackground', ({ data, error }) => {
  if (error) {
    console.log("Error bg", error)
    return;
  }
  if (data) {
    const { locations } = data;
    console.log("BGGGG->", locations[0].coords.latitude, locations[0].coords.longitude);
  }
});




export default App;

I had precisely the same problem and solved this by using and EventEmitter to dispatch the location updates to the UI component.

Top of file:

import EventEmitter from 'EventEmitter'

const locationEmitter = new EventEmitter();

didMount:

locationEmitter.on(LOCATION_UPDATE, (locationData) => {
    console.log('locationEmitter locationUpdate fired! locationData: ', locationData);
    let coordinatesAmount = locationData.newRouteCoordinates.length - 1;
    this.setState({
        latitude: locationData.newRouteCoordinates[coordinatesAmount - 1].latitude,
        longitude: locationData.newRouteCoordinates[coordinatesAmount - 1].longitude,
        routeCoordinates: this.state.routeCoordinates.concat(locationData.newRouteCoordinates)
    })
})

componentWillUnmount:

locationEmitter.off(LOCATION_UPDATE);

inside background task definition:

locationEmitter.emit(LOCATION_UPDATE, locationData)

This succesfully sends the location data from the background task, but I'm still stuck in the problem of how to make the background task send location update batches more often. My related post is here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM