DEV Community

Dayanand garg
Dayanand garg

Posted on • Edited on

How to track user location in background

Image description

In many mobile apps, it's important to track the user's location to provide location-based services or gather data for analytics purposes. However, tracking the location in the background and sending it to the server can be challenging, especially when the screen is locked or the app is in the background. In this tutorial, we'll learn how to update the user's location in every 15 minutes and send it to the server even when the screen is locked in a React Native app.

Prerequisites

Before we get started, make sure you have the following installed on your development machine:

Node.js (v10 or later)
React Native CLI
Android Studio (for Android development)
Xcode (for iOS development)

Step 1: Install necessary packages

First, let's install the necessary packages to track the user's location in the background and schedule a background task. Run the following commands in your terminal:



npm install @react-native-community/geolocation
npm install react-native-background-task


Enter fullscreen mode Exit fullscreen mode

Step 2: Grant permissions

Next, we need to grant the necessary permissions to access the device's location. Depending on your target platform, you need to add the following lines to your AndroidManifest.xml and Info.plist files:

AndroidManifest.xml:



<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />


Enter fullscreen mode Exit fullscreen mode

Info.plist:



<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is used to track your movements.</string>
<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
  <string>remote-notification</string>
  <string>location</string>
</array>


Enter fullscreen mode Exit fullscreen mode

These permissions allow the app to access the device's location even when the app is in the background or the screen is locked.

Step 3: Set up background location tracking

Now, let's set up the background location tracking using the Geolocation module from @react-native-community/geolocation. This module provides a way to watch the device's position in the background and receive updates at a given interval.

Here's an example of how you can set up the background location tracking:



import Geolocation from '@react-native-community/geolocation';

// Configure Geolocation
Geolocation.setRNConfiguration({
  authorizationLevel: 'always', // Request "always" location permission
  skipPermissionRequests: false, // Prompt for permission if not granted
});

// Watch for position updates
const watchId = Geolocation.watchPosition(
  position => {
    console.log(position);
    // Send the position data to the server
  },
  error => {
    console.log(error);
  },
  {
    distanceFilter: 10, // Minimum distance (in meters) to update the location
    interval: 900000, // Update interval (in milliseconds), which is 15 minutes
    fastestInterval: 300000, // Fastest update interval (in milliseconds)
    accuracy: {
      android: 'highAccuracy',
      ios: 'best',
    },
    showsBackgroundLocationIndicator: true,
    pausesLocationUpdatesAutomatically: false,
    activityType: 'fitness', // Specify the activity type (e.g., 'fitness' or 'other')
    useSignificantChanges: false,
    deferredUpdatesInterval: 0,
    deferredUpdatesDistance: 0,
    foregroundService: {
      notificationTitle: 'Tracking your location',
      notificationBody: 'Enable location tracking to continue', // Add a notification body
    },
  }
);

// To stop tracking (for example, when the component unmounts):
// Geolocation.clearWatch(watchId);



Enter fullscreen mode Exit fullscreen mode

By following the steps outlined in this tutorial, you can ensure that your app continues to track the user's location and provide relevant services even when the app is in the background or the screen is locked.

Top comments (4)

Collapse
 
ngvsang profile image
Nguyễn Viết Sáng

Hi, I don't see you use react-native-background-task, so what does it help?

Collapse
 
ofryl profile image
Collapse
 
eduardovargasleffa profile image
Eduardo Vargas Leffa Abrantes

and not worked for me

Collapse
 
jasim678 profile image
Jasim Khan

how to add geofence in this background running code i have 5 location i want make notification on entry and exit how can i achieve this