API reference
This page is the direct LocationTracker API: every method, event, and type from the public TypeScript surface. Use it when a screen, a headless task, or a custom store needs full control (HTTP config, geofences, schedules, the on-device queue, odometer, diagnostics).
Most apps never need to wire these by hand. Start with the React hooks. The hooks call this same module. How much control you take is up to you.
import LocationTracker, {
type LocationTrackerApi,
type Status,
type LocationEvent,
type SyncEvent,
type OpResult,
type TrackingProfile,
type HttpConfig,
} from 'react-native-background-location-pro-eval';
The default export is LocationTracker. Lifecycle and config methods return Promise<OpResult> and reject with the same code on failure. getStatus() and getOdometer() are synchronous. Results also arrive through events.
Methods at a glance
| Method | Purpose |
|---|---|
startTracking(serverUrl) | Start tracking and syncing to your backend |
stopTracking() | Stop tracking. Pending points stay on the device. |
getStatus() | Synchronous snapshot of all tracker state |
syncNow() | Force an immediate upload attempt |
validateServerUrl(url) | Preflight a URL without starting tracking |
setTrackingProfile(profile) | Change accuracy and battery trade-off live |
setSyncPolicy(...) | Tune batching, backoff and dead-lettering |
setHttpConfig(config) | Path, headers, body params, cellular sync |
setPersistencePolicy(...) | Cap how long / how many points stay on device |
setDemoMode(enabled) | Sync every 5 s instead of 30 s |
getCurrentPosition(...) | One-shot fix, not stored and not uploaded |
getQueueStats() / getLocations(...) / destroyLocations() | Inspect or clear the on-device queue |
getOdometer() / resetOdometer() | Distance since last reset |
addGeofence(s) / removeGeofence(s) / getGeofences() | Geofence registry |
setSchedule / startSchedule / stopSchedule | Weekly start/stop windows |
getDiagnostics() / setVerboseLogging | Support snapshot and logging |
requestLocationPermission(always) | Ask for When-In-Use or Always |
setMotionPermissionOptIn(enabled) | Android: Activity Recognition opt-in |
requestIgnoreBatteryOptimizations() | Battery exemption / Settings |
openExactAlarmSettings() | Exact alarms / Background App Refresh settings |
| Event emitters | onLocationUpdate, onSyncStatus, onHttp, onProviderChange, onGeofence, onTrackingStateChange, onConfigChange, onScheduleEdge |
Tracking
startTracking()
startTracking(serverUrl: string): Promise<OpResult>
Persists a valid base URL (http/https, no query or fragment), marks tracking as desired, and starts collection. Rejects with invalid_server_url.* or eval_blocked.
| Parameter | Type | Description |
|---|---|---|
serverUrl | string | Base URL of your backend. Points post to {serverUrl} plus the path from setHttpConfig (default /api/location/track). |
const result = await LocationTracker.startTracking('https://api.example.com');
// result.ok, result.code, result.message
- Call it while the app is in the foreground. Android does not allow a location foreground service to start from the background.
- Calling it again while tracking updates the server URL when validation succeeds.
- Prefer
validateServerUrlorgetTrackingStartContextbefore start when you want a soft check.
See Tracking lifecycle.
stopTracking()
stopTracking(): Promise<OpResult>
Clears the desired flag and stops collection after a final flush. Buffered points stay on the device and upload on the next startTracking().
await LocationTracker.stopTracking();
getStatus()
getStatus(): Status
Returns a Status snapshot. Synchronous and safe to call on every render or on a timer.
const {running, pending, authorization} = LocationTracker.getStatus();
syncNow()
syncNow(): Promise<OpResult>
Forces an immediate sync attempt. Still skipped while offline. Rejects with not_running when tracking is not active.
await LocationTracker.syncNow();
validateServerUrl()
validateServerUrl(url: string): Promise<ValidateServerUrlResult>
Validates a URL without starting tracking or changing persisted config. Always resolves so you can inspect ok / code / normalizedUrl without try/catch.
const v = await LocationTracker.validateServerUrl('https://api.example.com');
if (!v.ok) console.warn(v.code, v.message);
Configuration
setTrackingProfile()
setTrackingProfile(profile: string): Promise<OpResult> // pass a TrackingProfile value
Persisted and applied live. Rejects with invalid_profile and keeps the current profile.
await LocationTracker.setTrackingProfile('balanced');
See TrackingProfile.
setSyncPolicy()
setSyncPolicy(batchSize: number, maxBackoffMs: number, maxAttempts: number): Promise<OpResult>
| Parameter | Type | Description |
|---|---|---|
batchSize | number | Maximum points per request. |
maxBackoffMs | number | Cap on jittered exponential backoff between retries (ms). |
maxAttempts | number | Non-retryable 4xx rejections before a batch is dead-lettered. 0 means keep retrying. |
await LocationTracker.setSyncPolicy(100, 300_000, 5);
See Offline tracking and sync.
setHttpConfig()
setHttpConfig(config: HttpConfig): Promise<OpResult>
Replaces the whole HTTP config. Omitted fields return to their defaults.
type HttpConfig = {
path?: string; // default '/api/location/track'
headers?: Record<string, string>; // Content-Type, Idempotency-Key, X-Device-Id cannot be overridden
params?: Record<string, unknown>; // extra top-level JSON fields; deviceId, batchId, sentAt, points win
disableAutoSyncOnCellular?: boolean; // auto sync waits for Wi-Fi; syncNow and stop flush still upload
};
await LocationTracker.setHttpConfig({
path: '/v1/trips/points',
headers: {Authorization: 'Bearer …'},
params: {appVersion: '1.2.0'},
disableAutoSyncOnCellular: true,
});
setPersistencePolicy()
setPersistencePolicy(maxDaysToPersist: number, maxRecordsToPersist: number): Promise<OpResult>
Persisted. Drops pending points older than maxDaysToPersist, and drops the oldest pending points once more than maxRecordsToPersist are queued. 0 disables that limit.
await LocationTracker.setPersistencePolicy(14, 50_000);
setDemoMode()
setDemoMode(enabled: boolean): Promise<OpResult>
Persisted. Sync tick 5 s (demo) vs 30 s (default). Leave it off in production.
await LocationTracker.setDemoMode(__DEV__);
One-shot position and queue
getCurrentPosition()
getCurrentPosition(timeoutMs: number, maximumAgeMs: number): Promise<CurrentPosition>
One fresh fix, independent of tracking. Not stored and not uploaded. May resolve with a cached fix younger than maximumAgeMs. Rejects with timeout.
const fix = await LocationTracker.getCurrentPosition(10_000, 5_000);
getQueueStats()
getQueueStats(): Promise<QueueStats>
const {pending, synced, rejected, oldestPendingAt, newestAt} =
await LocationTracker.getQueueStats();
getLocations()
getLocations(status: string, limit: number, offset: number): Promise<StoredLocation[]>
status is pending | synced | rejected | all. Ordered oldest first.
const rows = await LocationTracker.getLocations('pending', 100, 0);
destroyLocations()
destroyLocations(): Promise<number>
Deletes every stored point, including pending ones. Resolves with the number deleted.
Odometer
getOdometer()
getOdometer(): number
Meters between accepted fixes since the last reset. Synchronous.
resetOdometer()
resetOdometer(): Promise<OpResult>
Geofences
addGeofences() / addGeofence()
addGeofences(geofences: GeofenceInput[]): Promise<number>
addGeofence(geofence: GeofenceInput): Promise<number>
Registers or replaces by identifier. Persisted across restarts. Resolves with the total number registered. Radius is clamped to at least 100 m.
await LocationTracker.addGeofence({
identifier: 'depot',
latitude: 12.97,
longitude: 77.59,
radius: 150,
notifyOnEntry: true,
notifyOnExit: true,
});
removeGeofences() / removeGeofence()
removeGeofences(identifiers: string[]): Promise<number>
removeGeofence(identifier: string): Promise<number>
An empty array removes every geofence.
getGeofences()
getGeofences(): Promise<Geofence[]>
Schedule
setSchedule()
setSchedule(schedule: string[]): Promise<OpResult>
Each entry is "<days> <HH:mm>-<HH:mm>" in local time. Days: 1 = Sunday … 7 = Saturday, a range like 2-6, or a list like 1,7.
await LocationTracker.setSchedule(['2-6 09:00-18:00', '1,7 10:00-14:00']);
startSchedule() / stopSchedule()
startSchedule(): Promise<OpResult>
stopSchedule(): Promise<OpResult>
startSchedule starts or stops tracking at each window edge until stopSchedule().
Diagnostics
getDiagnostics()
getDiagnostics(): Promise<Diagnostics>
Support snapshot. Header names only (no values). Fine coordinates are redacted unless verbose logging is on.
setVerboseLogging()
setVerboseLogging(enabled: boolean): Promise<OpResult>
Persisted. When true, logs may include fine coordinates. Defaults false outside demo mode.
Permissions and system settings
requestLocationPermission()
requestLocationPermission(always: boolean): void
Requests When-In-Use first. With always = true, escalates to Always once When-In-Use is granted, or opens Settings when the OS will no longer show the prompt.
LocationTracker.requestLocationPermission(true);
Read getStatus().authorization or listen to onProviderChange. See Android setup and iOS setup. Or use usePermissions.
setMotionPermissionOptIn()
setMotionPermissionOptIn(enabled: boolean): Promise<OpResult>
Android only. Opts in to Activity Recognition for the adaptive_low_power motion gate. No-op on iOS (Motion & Fitness is requested on demand by that profile).
requestIgnoreBatteryOptimizations()
requestIgnoreBatteryOptimizations(): void
Android asks for a battery exemption. iOS opens the app Settings page. Check getStatus().batteryUnrestricted afterwards.
openExactAlarmSettings()
openExactAlarmSettings(): void
Android opens Alarms & reminders. iOS opens app Settings (Background App Refresh). Check getStatus().exactAlarmsAllowed afterwards.
Events
Events are EventEmitter properties. They return a subscription with remove(). Always remove on unmount.
const sub = LocationTracker.onLocationUpdate(handler);
// later
sub.remove();
Events reach JS only while the JS runtime is alive. Collection and upload continue when the app is backgrounded or killed. When your app opens again, read getStatus() to catch up.
onLocationUpdate
readonly onLocationUpdate: EventEmitter<LocationEvent>
Fires once per accepted fix after it is saved on the device.
onSyncStatus
readonly onSyncStatus: EventEmitter<SyncEvent>
Connectivity, queue, sync outcome, and motion-gate changes.
onHttp
readonly onHttp: EventEmitter<HttpEvent>
One upload attempt of one batch (status, size, attempt, duration, error).
onProviderChange
readonly onProviderChange: EventEmitter<ProviderEvent>
Location authorization or the system location switch changed.
onGeofence
readonly onGeofence: EventEmitter<GeofenceEvent>
Enter / exit for a registered geofence.
onTrackingStateChange
readonly onTrackingStateChange: EventEmitter<TrackingStateEvent>
running / desired changed, with a reason string (for example js:startTracking or schedule:start).
onConfigChange
readonly onConfigChange: EventEmitter<ConfigChangeEvent>
Persisted config was committed and/or published to the sync path.
onScheduleEdge
readonly onScheduleEdge: EventEmitter<ScheduleEdgeEvent>
A schedule window started or stopped (action: start | stop).
Types
OpResult
type OpResult = {ok: boolean; code: string; message: string};
"ok" on success, otherwise a stable machine code such as invalid_server_url.scheme.
ValidateServerUrlResult
type ValidateServerUrlResult = {
ok: boolean;
code: string;
message: string;
normalizedUrl: string; // present when ok
};
TrackingProfile
type TrackingProfile = 'continuous_fitness' | 'balanced' | 'adaptive_low_power';
| Value | Behavior | Best for |
|---|---|---|
continuous_fitness | Never pauses on its own. 5 m distance filter until stopTracking(). | Running, cycling, workout recording |
balanced | Always subscribed, with a 20 m displacement gate. | Delivery and ride tracking |
adaptive_low_power (default) | balanced plus a motion gate that parks GPS while stationary. Sensor failure falls back to balanced. | All-day and fleet tracking |
LocationEvent
| Field | Type | Description |
|---|---|---|
id | string | Unique point ID. Same as points[].id in the backend payload. |
latitude / longitude | number | Degrees. |
accuracy | number | Horizontal accuracy radius in meters. |
speed | number | Meters per second. |
timestamp | number | Epoch ms. |
pending | number | Points on device not yet acknowledged, including this one. |
SyncEvent
| Field | Type | Description |
|---|---|---|
running | boolean | Collecting right now. |
online | boolean | Device has connectivity. |
pending / synced / rejected | number | Queue counters. |
lastSyncAt | number | Epoch ms of last success. 0 if none. |
retryAttempt / nextRetryAt | number | Retry state. |
lastSyncError | string | e.g. http_503 or TimedOut. Empty after success. |
configValidationCode | string | Last config validation/apply code. |
motionGateActive | boolean | GPS parked while stationary. |
motionState | string | stationary, walking, running, driving, cycling, moving, unknown, unsupported. |
message | string | Human-readable status. Errors use a [code] prefix. |
Status
Returned by getStatus().
Tracking
| Field | Type | Description |
|---|---|---|
running | boolean | Collecting right now. |
desired | boolean | Tracking was requested and not stopped; recovery keeps the pipeline alive while true. |
trackingProfile | string | Active TrackingProfile. |
lastLocationAt | number | Epoch ms of last accepted fix. |
message | string | Human-readable status. |
buildTier | string | Evaluation: 'debug' while evaluating, 'release' when evaluation is unavailable. |
odometer | number | Meters since last resetOdometer(). |
geofenceCount | number | Registered geofences. |
scheduleEnabled | boolean | Schedule is driving start/stop. |
persistedConfigVersion / activeConfigVersion | number | Config commit vs publish versions. |
configValidationCode / configValidationMessage | string | Last config validation outcome. |
verboseLogging | boolean | Fine coordinates may appear in logs. |
Sync
| Field | Type | Description |
|---|---|---|
online | boolean | Connectivity. |
pending / synced / rejected | number | Queue counters. |
lastSyncAt / retryAttempt / nextRetryAt | number | Sync timing. |
lastSyncError | string | Last failure code/message. |
serverUrl / deviceId | string | Target URL and stable install id. |
demoMode | boolean | 5 s vs 30 s sync tick. |
Permissions and system health
| Field | Type | Description |
|---|---|---|
authorization | string | notDetermined, whenInUse, always, denied, restricted. |
preciseLocation | boolean | Precise accuracy granted. |
exactAlarmsAllowed | boolean | Android: exact alarms. iOS: Background App Refresh available. |
batteryUnrestricted | boolean | Android: battery exemption. iOS: Low Power Mode off. |
motionPermission | string | granted, denied, notRequested, unavailable. |
motionPermissionOptIn | boolean | Android opt-in. Always false on iOS. |
motionGateActive / motionState / motionSource | — | Motion gate snapshot. |
Other exported types
| Type | Role |
|---|---|
HttpConfig | setHttpConfig shape (from the package entry). |
CurrentPosition | One-shot fix (heading, altitude, …). |
QueueStats | Aggregate queue counters. |
StoredLocation | On-device row from getLocations. |
HttpEvent | One batch upload attempt. |
ProviderEvent | Authorization / services change. |
Geofence / GeofenceInput | Geofence record (input makes notify flags optional). |
GeofenceEvent | Enter / exit payload. |
TrackingStateEvent | Lifecycle reason + profile. |
ConfigChangeEvent | Config version / validation. |
ScheduleEdgeEvent | Schedule window edge. |
Diagnostics | Support snapshot from getDiagnostics. |
LocationTrackerApi | Typed default export (includes addGeofence helpers). |
Mocking in Jest
import type {LocationTrackerApi, Status} from 'react-native-background-location-pro-eval';
const subscription = {remove: jest.fn()};
const ok = {ok: true, code: 'ok', message: 'ok'};
const mock: Partial<LocationTrackerApi> = {
startTracking: jest.fn(async () => ok),
stopTracking: jest.fn(async () => ok),
syncNow: jest.fn(async () => ok),
setDemoMode: jest.fn(async () => ok),
setTrackingProfile: jest.fn(async () => ok),
setSyncPolicy: jest.fn(async () => ok),
setHttpConfig: jest.fn(async () => ok),
validateServerUrl: jest.fn(async () => ({
ok: true,
code: 'ok',
message: 'ok',
normalizedUrl: 'https://api.example.com',
})),
requestLocationPermission: jest.fn(),
getStatus: jest.fn(
(): Partial<Status> => ({running: false, desired: false, pending: 0}),
),
onLocationUpdate: jest.fn(() => subscription),
onSyncStatus: jest.fn(() => subscription),
onHttp: jest.fn(() => subscription),
onProviderChange: jest.fn(() => subscription),
onGeofence: jest.fn(() => subscription),
onTrackingStateChange: jest.fn(() => subscription),
onConfigChange: jest.fn(() => subscription),
onScheduleEdge: jest.fn(() => subscription),
};
export default mock;