Examples
Copy-paste patterns for the most common integrations. Start with the hooks. Use the imperative API when a feature needs more control.
Tracking screen with the built-in hooks
import React from 'react';
import {Alert, Button, SafeAreaView, Text} from 'react-native';
import {
useLocationTracking,
useLocationUpdates,
usePermissions,
} from 'react-native-background-location-pro-eval';
const SERVER_URL = 'https://api.example.com';
export function TrackingScreen() {
const permissions = usePermissions();
const {
isTracking,
isStarting,
isStopping,
status,
startTracking,
stopTracking,
} = useLocationTracking({serverUrl: SERVER_URL});
const {latestLocation} = useLocationUpdates({maxItems: 50});
const onStart = async () => {
if (status.buildTier === 'release') {
Alert.alert('Evaluation build', 'Tracking is available in debug builds only.');
return;
}
if (!permissions.hasBackgroundAlways) {
Alert.alert(
'Allow background location',
'To record your trip while the app is closed, choose "Allow all the time" / "Always".',
[
{text: 'Not now', style: 'cancel'},
{
text: 'Continue',
onPress: () =>
permissions.hasForeground
? permissions.requestAlways()
: permissions.requestWhenInUse(),
},
],
);
return;
}
await startTracking();
};
return (
<SafeAreaView style={{padding: 24, gap: 12}}>
<Text>{permissions.guidance.message}</Text>
<Button
title={isTracking ? 'Stop tracking' : 'Start tracking'}
disabled={isStarting || isStopping}
onPress={() => (isTracking ? stopTracking() : onStart())}
/>
<Text>
{latestLocation
? `${latestLocation.latitude.toFixed(5)}, ${latestLocation.longitude.toFixed(5)}`
: 'No points yet'}
</Text>
<Text>
{status.pending} pending · {status.synced} synced
</Text>
</SafeAreaView>
);
}
Show the live route on a map
Using react-native-maps and useLocationUpdates:
import React, {useMemo} from 'react';
import MapView, {Polyline} from 'react-native-maps';
import {useLocationUpdates} from 'react-native-background-location-pro-eval';
export function LiveRoute() {
const {locations} = useLocationUpdates({maxItems: 500});
const path = useMemo(
() =>
locations
.filter(p => p.accuracy <= 50)
.map(p => ({latitude: p.latitude, longitude: p.longitude}))
.reverse(),
[locations],
);
const last = path[path.length - 1];
return (
<MapView
style={{flex: 1}}
region={
last ? {...last, latitudeDelta: 0.01, longitudeDelta: 0.01} : undefined
}>
<Polyline coordinates={path} strokeWidth={4} />
</MapView>
);
}
Sync status badge
import React from 'react';
import {Text} from 'react-native';
import {useLocationTracking} from 'react-native-background-location-pro-eval';
export function SyncBadge() {
const {lastSync: e} = useLocationTracking({reconcileIntervalMs: 0});
if (!e) return null;
if (!e.online) return <Text>Offline · {e.pending} saved on device</Text>;
if (e.retryAttempt > 0) {
const inSec = Math.max(0, Math.round((e.nextRetryAt - Date.now()) / 1000));
return (
<Text>
Retrying in {inSec}s · {e.pending} pending
</Text>
);
}
return (
<Text>
Synced {e.synced} · {e.pending} pending
</Text>
);
}
Direct handlers for more control
When a feature needs HTTP config, geofences, a schedule, or queue inspection, call LocationTracker directly. Hooks still work for the rest of the UI.
import LocationTracker from 'react-native-background-location-pro-eval';
export async function hardenUploads(token: string) {
await LocationTracker.setHttpConfig({
path: '/v1/trips/points',
headers: {Authorization: `Bearer ${token}`},
params: {client: 'driver-app'},
disableAutoSyncOnCellular: false,
});
await LocationTracker.setSyncPolicy(150, 600_000, 0);
await LocationTracker.setTrackingProfile('adaptive_low_power');
await LocationTracker.setDemoMode(false);
}
export async function registerDepotGeofence() {
await LocationTracker.addGeofence({
identifier: 'depot',
latitude: 12.97,
longitude: 77.59,
radius: 150,
});
}
export async function workdaySchedule() {
await LocationTracker.setSchedule(['2-6 09:00-18:00']);
await LocationTracker.startSchedule();
}
Send points to your backend
The tracker uploads to your server even while the app is killed, so you do not need to forward points from JS. Point it at your API and implement one endpoint:
await LocationTracker.startTracking('https://api.example.com');
// -> POST https://api.example.com/api/location/track (or your setHttpConfig path)
const express = require('express');
const app = express();
app.use(express.json({limit: '1mb'}));
const seenBatches = new Set(); // use a database unique index in production
app.post('/api/location/track', (req, res) => {
const {batchId, deviceId, points} = req.body;
if (seenBatches.has(batchId)) {
return res.json({ok: true, duplicate: true});
}
seenBatches.add(batchId);
for (const p of points) {
console.log(deviceId, new Date(p.timestamp).toISOString(), p.lat, p.lng, `±${p.accuracy}m`);
}
res.json({ok: true, accepted: points.length});
});
app.listen(3000);
Respond 2xx to acknowledge, 5xx or 429 (optionally with Retry-After) to ask for a retry. The full contract is in Offline tracking and sync.
Put a small adapter endpoint in front of it, or use a serverless function that receives your path and forwards points to your existing service. In the licensed edition you can also change the request format in the source you own.
Switch profiles by use case
import LocationTracker, {type TrackingProfile} from 'react-native-background-location-pro-eval';
function profileFor(mode: 'workout' | 'delivery' | 'all-day'): TrackingProfile {
switch (mode) {
case 'workout':
return 'continuous_fitness';
case 'delivery':
return 'balanced';
case 'all-day':
return 'adaptive_low_power';
}
}
await LocationTracker.setTrackingProfile(profileFor('delivery')); // applied live
Restore UI state on launch
Tracking may have continued, or been revived, while your app was closed. Read status instead of storing your own flag:
const {desired, running, pending} = LocationTracker.getStatus();
// or: const {status, isTracking} = useLocationTracking();
Health check screen
import React from 'react';
import {Button, Text, View} from 'react-native';
import {useLocationTracking, usePermissions} from 'react-native-background-location-pro-eval';
import LocationTracker from 'react-native-background-location-pro-eval';
export function TrackerHealth() {
const {status: s, refreshStatus} = useLocationTracking();
const permissions = usePermissions();
return (
<View style={{gap: 8, padding: 16}}>
<Text>
Location permission: {s.authorization}{' '}
{s.preciseLocation ? '(precise)' : '(approximate)'}
</Text>
<Text>Background recovery available: {String(s.exactAlarmsAllowed)}</Text>
<Text>Battery unrestricted: {String(s.batteryUnrestricted)}</Text>
<Text>
Motion: {s.motionState} (gate {s.motionGateActive ? 'parked' : 'active'})
</Text>
<Text>Odometer: {s.odometer.toFixed(0)} m</Text>
<Text>Last sync error: {s.lastSyncError || 'none'}</Text>
{permissions.guidance.code !== 'ok' && (
<Button
title="Fix location permission"
onPress={() =>
permissions.hasForeground
? permissions.requestAlways()
: permissions.requestWhenInUse()
}
/>
)}
{!s.exactAlarmsAllowed && (
<Button
title="Fix background recovery"
onPress={() => LocationTracker.openExactAlarmSettings()}
/>
)}
{!s.batteryUnrestricted && (
<Button
title="Remove battery restrictions"
onPress={() => LocationTracker.requestIgnoreBatteryOptimizations()}
/>
)}
<Button
title="Refresh"
onPress={() => {
refreshStatus();
permissions.refresh();
}}
/>
<Button
title="Copy diagnostics"
onPress={async () => {
const d = await LocationTracker.getDiagnostics();
console.log(JSON.stringify(d, null, 2));
}}
/>
</View>
);
}