React Native

Handling Geolocation Updates in Background on iOS and Android


Introduction

Geolocation tracking brings an important contribution towards enabling applications such as navigation, fitness tracking, and location-based services. Among the complications that arise with background geolocation tracking is how to achieve accuracy and efficiency amid platform constraints. In this we explores how to handle geolocation updates in the background on both iOS and Android using react-native-geolocation-service and @darron1217/react-native-background-geolocation.

Why Background Geolocation?

1. Enabling Real-Time Location-Based Features

Background geolocation allows apps to provide uninterrupted services such as route tracking, geofencing, and location-based notifications, even when the app is not actively used.

2. Overcoming Platform-Specific Challenges

  • iOS: Strict background execution policies require special permissions and configurations to keep the app running in the background.
  • Android: Android's Doze mode and background restrictions demand careful implementation to ensure reliable tracking.

3. Balancing Accuracy and Battery Efficiency

Continuous geolocation tracking can drain the battery. Optimised implementations help strike a balance between location accuracy and energy consumption.

Configuration

Update Info.plist

Add the necessary keys for location usage and background execution:

<key>NSLocationWhenInUseUsageDescription</key><string>We need your location to provide better services.</string><key>NSLocationAlwaysUsageDescription</key><string>We need your location to provide better services even in the background.</string><key>UIBackgroundModes</key><array> <string>Location</string></array>

 

Enable Background Location Updates

Ensure allowsBackgroundLocationUpdates is set to true in the native implementation:

locationManager.allowsBackgroundLocationUpdates = truelocationManager.pausesLocationUpdatesAutomatically = false

 

Configuring Android for Background Geolocation

Update AndroidManifest.xml

Add the required permissions and background location configuration:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" /><application> <service android:name="com.transistorsoft.locationmanager.BackgroundGeoLocationService" android:enabled="true" android:exported="true" android:permission="android.permission.FOREGROUND_SERVICE" /></application>

 

Implementing Geolocation in React Native

Requesting Permissions

Use react-native-geolocation-service to request location permissions.

Real-Time Location Tracking

Track location updates using react-native-geolocation-service’s watchPosition function.

import Geolocation from 'react-native-geolocation-service';import { PermissionsAndroid, Platform } from 'react-native';import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';async function requestLocationPermission() { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { title: "Location Access Permission", message: "We need your permission to access your location.", buttonPositive: "OK" } ); return granted === PermissionsAndroid.RESULTS.GRANTED; } else { const status = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE); if (status === RESULTS.GRANTED) { return true; } else if (status === RESULTS.DENIED) { console.log("Location permission denied. Ask again if necessary."); return false; } else if (status === RESULTS.BLOCKED) { console.log("Location permission is blocked. Redirect user to settings."); return false; } else { return false; } }}function watchLocation() { Geolocation.watchPosition( (position) => { console.log("Location update:", position); // Use location lat long }, (error) => { console.error("Errors", error); }, { enableHighAccuracy: true, distanceFilter: 10, interval: 5000, fastestInterval: 2000, showLocationDialog: true, } );}

 

Background Geolocation Tracking

Use @darron1217/react-native-background-geolocation for background location updates.

Initialize Background Geolocation

Configure and start background tracking:

import BackgroundGeolocation from '@darron1217/react-native-background-geolocation';BackgroundGeolocation.on('location', (location) => { console.log("Background Locations", location); // Send location to server or handle it});BackgroundGeolocation.on('error', (error) => { console.error("Background location errors", error);});BackgroundGeolocation.ready({ desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH, distanceFilter: 10, stopTimeout: 1, debug: true, stopOnTerminate: false, startOnBoot: true,}).then(() => { BackgroundGeolocation.start();});

 

Optimizing for Battery Efficiency

  • Use a distanceFilter to limit location updates to significant movements.

  • Avoid high-accuracy tracking unless necessary.

  • Stop tracking when the app is in an idle state.

Conclusion

In order to deliver the location-based services seamless, the handling of geolocation updates in the background is important. We can implement real time tracking applications using react-native-geolocation-service along with background updates through @darron1217/react-native-background-geolocation, which can help you develop solid geolocation features in both iOS and Android applications. With proper configurations and optimizations, your app can provide accurate tracking without significantly impacting battery life.

 

Ready to transform your business with our technology solutions? Contact Us today to Leverage Our React Native Expertise.

 

0

React Native

Related Center Of Excellence