react-native-background-live-tracking
v1.0.3
Published
Production-ready Android background GPS tracking with REST/WebSocket, offline queue, and foreground service.
Maintainers
Readme
react-native-background-live-tracking
Android-only React Native library for continuous driver GPS tracking in the foreground, background, and after the user swipes the app away. Locations are sent to your backend over REST and optionally WebSocket or Socket.IO, with an offline queue, retries, and a foreground service with a persistent notification.
iOS autolinking is disabled; the JavaScript API no-ops on iOS so your monorepo can still import the module safely.
Features
- Fused location updates with configurable interval (milliseconds)
START_STICKYforeground service; optional restart after boot if tracking was active- REST
POST(JSON body) on every fix, plus optional real-time channel - Offline JSONL queue on disk and periodic flush + per-request retries
- Permission checks with clear promise rejections
- Optional
openBatterySettings()to request ignore battery optimizations - JS events:
Tracking.addLocationListener,Tracking.addStatusListener,Tracking.isActive() - Optional notification map preview: static map image via Google Static Maps (not a live map)
Why not a live map like iOS / Uber on the lock screen?
- iOS “Live Activities” use ActivityKit with SwiftUI and MapKit. That is a separate system UI; it is not how Android works.
- Android foreground-service notifications are built from RemoteViews: mostly
TextView/ImageView. You cannot put a real, continuously updating Google Map (MapView) inside the notification shade the same way. - Ride apps on Android usually combine a text notification plus in-app or full-screen UI. A similar visual in the tray is normally a bitmap: either a Static Maps image (what we support optionally) or your own server-rendered snapshot.
Optional: map snapshot in the expanded notification
Enable the Google Static Maps API on a Cloud project (billing required). Then:
await Tracking.start({
driverId: 'driver-123',
interval: 5000,
serverUrl: 'https://api.example.com/v1/drivers/location',
notificationTitle: 'Driver En Route',
notificationBody: 'Live location is active',
notificationMapPreview: true,
googleStaticMapsApiKey: 'YOUR_KEY',
pickup: { latitude: 12.97, longitude: 77.59 }, // optional second marker
});The image appears in the expanded notification (pull down / long press depending on OEM). Updates are throttled (about every 45s) to limit API usage.
Install
npm install react-native-background-live-tracking
# or
yarn add react-native-background-live-trackingMetro (monorepo / file: dependency)
If the package lives outside your app root, add its folder to watchFolders in metro.config.js (see this repo’s root config).
Autolinking
Android is configured via react-native.config.js (TrackingPackage). Rebuild the native app after install.
Use in your app (any developer)
Import from your app code—not from inside this library. Use any screen or module that should start/stop tracking (for example App.tsx, src/screens/DriverScreen.tsx, or src/services/liveTracking.ts).
import { Tracking } from 'react-native-background-live-tracking';serverUrl,restHeaders(e.g. auth tokens), anddriverIdcome from your backend and app state.googleStaticMapsApiKey(optional map preview) is never built into the npm package. Each app uses its own Google Cloud project and key; pass it only inTracking.startor load it from env / secure config in your repo.
Permissions
The library declares the required permissions. Your app must request at runtime (in order on Android 10+):
ACCESS_FINE_LOCATIONACCESS_BACKGROUND_LOCATION(needed when the app is killed)POST_NOTIFICATIONS(Android 13+)
Use PermissionsAndroid or your preferred permission helper before calling Tracking.start.
JavaScript API
import { Tracking } from 'react-native-background-live-tracking';
await Tracking.start({
driverId: 'driver-123',
interval: 5000, // milliseconds (e.g. 5 seconds)
serverUrl: 'https://api.example.com/v1/drivers/location',
socketUrl: 'wss://realtime.example.com/driver', // optional
socketTransport: 'websocket', // optional: 'websocket' | 'socket.io' | omit to auto-detect
notificationTitle: 'Driver En Route',
notificationBody: 'Sharing live location',
autoStartOnBoot: true,
restHeaders: { Authorization: 'Bearer …' },
notificationMapPreview: false,
googleStaticMapsApiKey: '',
});
await Tracking.stop();
const active = await Tracking.isActive();Events
const sub = Tracking.addLocationListener((loc) => {
// { latitude, longitude, timestamp, driverId, accuracy, speed, bearing }
});
sub.remove();
Tracking.addStatusListener(({ active }) => { ... });Battery optimization
await Tracking.openBatterySettings();OEMs may still restrict background work; combining a foreground service + user opt-out of optimization is the practical maximum on stock Android.
Backend contract
REST
POST to serverUrl with Content-Type: application/json and body:
{
"latitude": 19.076,
"longitude": 72.8777,
"timestamp": 1711728000123,
"driverId": "driver-123",
"accuracy": 12.5,
"speed": 8.2,
"bearing": 90.0
}Optional headers come from restHeaders.
WebSocket
When socketTransport is websocket (or inferred), each fix is sent as a text frame containing the same JSON string. Use wss:// or ws:// URLs (or https:// / http://, which are normalized to WebSocket schemes).
Socket.IO
When socketTransport is socket.io (or the URL suggests it), the client connects with the socket.io-java-client and emits event name location with a JSON object payload (same fields as above). Point socketUrl at your server origin, e.g. https://api.example.com (path /socket.io is default).
Native implementation notes
- Service:
LocationForegroundService,foregroundServiceType="location" - Location: Google Play services
FusedLocationProviderClient, balanced power by default (tunable in native code if you fork) - Boot:
BootCompletedReceiverrestarts the service whenautoStartOnBootis true and tracking was active - Queue:
filesDir/rn_blt_location_queue.jsonl, capped length 2000
Example app
This repository’s root React Native app depends on the package via file:./packages/react-native-background-live-tracking and includes a minimal driver-style UI in App.tsx.
Changelog
1.0.1
- Richer
package.json(exports,react-nativeentry,repository/bugsplaceholders—replaceyour-usernamewith your GitHub). - README: where to import the API and that map/server URLs are per-app, not fixed in the package.
1.0.0
- Initial release: Android foreground tracking, REST / WebSocket / Socket.IO, queue, optional Static Maps notification preview.
License
MIT
