BackgroundGeolocation¶
Primary SDK API — the single entry point for all geolocation, geofencing, HTTP sync, and configuration operations.
Contents¶
Overview¶
The SDK operates around a motion-based state machine: it tracks aggressively while the device is moving and pauses location services when stationary, delivering high-quality background tracking with minimal battery impact.
| Area | Key methods |
|---|---|
| Lifecycle | ready, start, stop, setConfig, reset |
| Location | getCurrentPosition, watchPosition, getOdometer |
| Geofencing | addGeofence, startGeofences, onGeofence |
| Events | onLocation, onMotionChange, onHttp, onProviderChange |
| Persistence | getLocations, getCount, sync, destroyLocations |
| Background tasks | startBackgroundTask, stopBackgroundTask |
Lifecycle¶
Think of the SDK like a stereo receiver:
-
Wiring the speakers — Register event listeners (
onLocation,onGeofence, etc.) before callingready. The SDK buffers events untilreadyresolves, so listeners registered afterward may miss them. You do not need to remove listeners when you callstop— the SDK simply stops emitting events when it isn't running. -
Plugging in the power cord —
readyinitializes the SDK, restores persisted state, and applies your configuration. Call it once per launch, before any method that acquires a location or requests permissions. Your config is not applied untilreadyresolves. -
The power button —
startandstopbegin and halt location tracking. The SDK persists its enabled state across launches. If the app is terminated while tracking is active, the next call toreadywill automatically resume tracking — you do not need to callstartagain.
Always call ready on every launch — no exceptions. The SDK buffers all events from the
moment the app starts, and holds them until ready is called. If your app launches and
never calls ready, the SDK sits silently waiting: no events fire, no locations are
recorded, no uploads are attempted. It does not matter whether tracking was already active
from a previous session — ready is the signal that tells the SDK your app is alive and
listening. This is why the method is named ready.
Calling methods before ready resolves is perfectly fine, provided they do not request
a location or trigger a permission dialog. Methods that only read from the SDK's SQLite
database are safe — for example getState, getLocations, getGeofences,
removeGeofences. Avoid start, requestPermission, getCurrentPosition, and
watchPosition until after ready resolves. The SDK defaults apply until your config
arrives — calling a permission-sensitive method too early will use those defaults, not
your configured values.
Configuration¶
The SDK uses a compound-configuration model. Options are grouped into typed sub-interfaces (GeoConfig, HttpConfig, AppConfig, etc.) passed as a single Config object. All SDK constants are available as strongly-typed enum namespaces on the default export:
import BackgroundGeolocation, {
Config,
GeoConfig,
HttpConfig
} from "react-native-background-geolocation";
// Register event-listeners before calling .ready()
BackgroundGeolocation.onLocation((location) => {
console.log("[onLocation]", location);
});
const config: Config = {
geolocation: {
desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High,
distanceFilter: 20
},
http: {
url: "https://example.com/locations",
autoSync: true
},
persistence: {
maxDaysToPersist: 7
}
};
BackgroundGeolocation.ready(config);
Events¶
Each onX method returns a Subscription that must be removed when
no longer needed:
These can also be imported individually¶
BackgroundGeolocation.onLocation((location) => {
console.log("New location:", location);
});
BackgroundGeolocation.onMotionChange((event) => {
console.log("Device is moving?", event.isMoving);
});
Examples¶
import BackgroundGeolocation from "react-native-background-geolocation";
const state = await BackgroundGeolocation.ready({
geolocation: { distanceFilter: 10 },
http: { url: "https://example.com/locations", autoSync: true }
});
if (!state.enabled) {
await BackgroundGeolocation.start();
}
Compound configuration¶
import BackgroundGeolocation, {
Config,
GeoConfig,
HttpConfig
} from "{{pluginName}}";
// Register event-listeners before calling .ready()
BackgroundGeolocation.onLocation((location) => {
console.log("[onLocation]", location);
});
const config: Config = {
geolocation: {
desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High,
distanceFilter: 20
},
http: {
url: "https://example.com/locations",
autoSync: true
},
persistence: {
maxDaysToPersist: 7
}
};
BackgroundGeolocation.ready(config);
Event listeners¶
BackgroundGeolocation.onLocation((location) => {
console.log("New location:", location);
});
BackgroundGeolocation.onMotionChange((event) => {
console.log("Device is moving?", event.isMoving);
});
Removing event listeners¶
Getting started¶
import BackgroundGeolocation from "{{pluginName}}";
const state = await BackgroundGeolocation.ready({
geolocation: { distanceFilter: 10 },
http: { url: "https://example.com/locations", autoSync: true }
});
if (!state.enabled) {
await BackgroundGeolocation.start();
}
Events¶
onActivityChange¶
onActivityChange(cb: (event:MotionActivityEvent) => void):Subscription;
Subscribe to motion-activity changes.
Fires each time the activity-recognition system reports a new activity
(still, on_foot, in_vehicle, on_bicycle, running).
Android¶
MotionActivityEvent.confidence always reports 100.
const subscription = BackgroundGeolocation.onActivityChange((event) => {
console.log("[onActivityChange] ", event);
});
activitychange
onAuthorization¶
onAuthorization(cb: (event:AuthorizationEvent) => void):Subscription;
Subscribe to Config.authorization events.
Fires when AuthorizationConfig.refreshUrl responds, either
successfully or not. On success, AuthorizationEvent.success is
true and AuthorizationEvent.response contains the decoded JSON
response. On failure, AuthorizationEvent.error contains the error
message.
const subscription = BackgroundGeolocation.onAuthorization((event) => {
if (event.success) {
console.log("[authorization] SUCCESS: ", event.response);
} else {
console.log("[authorization] ERROR: ", event.error);
}
});
authorization
onConnectivityChange¶
onConnectivityChange(cb: (event:ConnectivityChangeEvent) => void):Subscription;
Subscribe to network connectivity changes.
Fires when the device's network connectivity transitions between connected
and disconnected. By default, the SDK also fires this event at
start time with the current connectivity state. When connectivity
is restored and the SDK has queued locations, it automatically initiates
an upload to HttpConfig.url.
const subscription = BackgroundGeolocation.onConnectivityChange((event) => {
console.log("[onConnectivityChange] ", event);
});
connectivitychange
onEnabledChange¶
onEnabledChange(cb: (enabled: boolean) => void):Subscription;
Subscribe to changes in plugin State.enabled.
Fires when State.enabled changes. Calling start or
stop triggers this event.
const subscription = BackgroundGeolocation.onEnabledChange((isEnabled) => {
console.log("[onEnabledChange] isEnabled? ", isEnabled);
});
enabledchange
onGeofence¶
onGeofence(cb: (event:GeofenceEvent) => void):Subscription;
Subscribe to geofence transition events.
Fires when any monitored geofence crossing occurs.
See also
- 📘 Geofencing Guide
const subscription = BackgroundGeolocation.onGeofence((event) => {
console.log("[onGeofence] ", event);
});
geofence
onGeofencesChange¶
onGeofencesChange(cb: (event:GeofencesChangeEvent) => void):Subscription;
Subscribe to changes in the set of actively monitored geofences.
Fires when the SDK's active geofence set changes. The SDK can monitor any number of geofences in its database — even thousands — despite native platform limits (20 for iOS; 100 for Android). It achieves this with a geospatial query that activates only the geofences nearest to the device's current location (see GeoConfig.geofenceProximityRadius). When the device is moving, the query runs periodically and the active set may change — that change triggers this event.
See also
- 📘 Geofencing Guide
const subscription = BackgroundGeolocation.onGeofencesChange((event) => {
const on = event.on; // newly activated geofences
const off = event.off; // deactivated geofence identifiers
// Create map circles
on.forEach((geofence) => {
createGeofenceMarker(geofence);
});
// Remove map circles
off.forEach((identifier) => {
removeGeofenceMarker(identifier);
});
});
geofenceschange
onHeartbeat¶
onHeartbeat(cb: (event:HeartbeatEvent) => void):Subscription;
Subscribe to periodic heartbeat events.
Fires at each AppConfig.heartbeatInterval while the device is in
the stationary state. On iOS, AppConfig.preventSuspend must
also be true to receive heartbeats in the background.
Note
The Location provided by the HeartbeatEvent is only the
last-known location — the heartbeat does not engage location services. To
fetch a fresh location inside your callback, call getCurrentPosition.
BackgroundGeolocation.ready({
app: {
heartbeatInterval: 60,
preventSuspend: true // required for iOS
}
});
const subscription = BackgroundGeolocation.onHeartbeat((event) => {
console.log("[onHeartbeat] ", event);
// Optionally fetch a fresh location.
BackgroundGeolocation.getCurrentPosition({
samples: 1,
persist: true
}).then((location) => {
console.log("[getCurrentPosition] ", location);
});
});
heartbeat
onHttp¶
onHttp(cb: (event:HttpEvent) => void):Subscription;
Subscribe to HTTP responses from your server HttpConfig.url.
See also
- HTTP Guide
const subscription = BackgroundGeolocation.onHttp((response) => {
const status = response.status;
const success = response.success;
const responseText = response.responseText;
console.log("[onHttp] ", response);
});
http
onLocation¶
onLocation(cb: (location:Location) => void, onError?: (err:LocationError) => void):Subscription;
Subscribe to location events.
Every location recorded by the SDK is delivered to your callback, including
locations from onMotionChange, getCurrentPosition, and
watchPosition.
Error Codes¶
If the native location API fails, the error callback receives a LocationError code.
Note
During onMotionChange and getCurrentPosition, the SDK
requests multiple location samples to find the most accurate fix. These
intermediate samples are not persisted, but are delivered to this
callback with Location.sample set to true. Filter out sample
locations before manually posting to your server.
const subscription = BackgroundGeolocation.onLocation((location) => {
console.log("[onLocation] success: ", location);
}, (error) => {
console.log("[onLocation] ERROR: ", error);
});
location
onMotionChange¶
onMotionChange(cb: (event:MotionChangeEvent) => void):Subscription;
Subscribe to motion-change events.
Fires each time the device transitions between the moving and stationary states.
Warning
When a motion-change event fires, HttpConfig.autoSyncThreshold is ignored — all queued locations are uploaded immediately. The SDK flushes eagerly before going dormant (moving→stationary) and immediately after waking up (stationary→moving).
See also - GeoConfig.stopTimeout
const subscription = BackgroundGeolocation.onMotionChange((event: MotionChangeEvent) => {
if (event.isMoving) {
console.log("[onMotionChange] Device has just started MOVING ", event.location);
} else {
console.log("[onMotionChange] Device has just STOPPED: ", event.location);
}
});
motionchange
onNotificationAction¶
onNotificationAction(cb: (buttonId: string) => void):Subscription;
Android only Subscribe to button-click actions on the Android foreground-service notification.
Fires when the user taps a button defined in a custom NotificationConfig.layout.
onPowerSaveChange¶
onPowerSaveChange(cb: (enabled: boolean) => void):Subscription;
Subscribe to OS power-saving mode changes.
Fires when the operating system's power-saving mode is enabled or disabled. Power-saving mode can throttle background services such as GPS and HTTP uploads.
See also
- isPowerSaveMode
iOS¶
Power Saving mode is enabled manually in Settings → Battery or via an automatic OS prompt.

Android¶
Battery Saver is enabled manually in Settings → Battery → Battery Saver or automatically when the battery drops below a configured threshold.

const subscription = BackgroundGeolocation.onPowerSaveChange((isPowerSaveMode) => {
console.log("[onPowerSaveChange]: ", isPowerSaveMode);
});
powersavechange
onProviderChange¶
onProviderChange(cb: (event:ProviderChangeEvent) => void):Subscription;
Subscribe to location-services authorization changes.
Fires whenever the state of the device's location-services authorization
changes (e.g. GPS enabled, WiFi-only, permission revoked). The SDK also
fires this event immediately after ready completes, so you always
receive the current authorization state on each app launch.
See also
- getProviderState
const subscription = BackgroundGeolocation.onProviderChange((event) => {
console.log("[onProviderChange]: ", event);
switch (event.status) {
case BackgroundGeolocation.AuthorizationStatus.Denied:
// Android & iOS
console.log("- Location authorization denied");
break;
case BackgroundGeolocation.AuthorizationStatus.Always:
// Android & iOS
console.log("- Location always granted");
break;
case BackgroundGeolocation.AuthorizationStatus.WhenInUse:
// iOS only
console.log("- Location WhenInUse granted");
break;
}
});
providerchange
onSchedule¶
onSchedule(cb: (state:State) => void):Subscription;
Subscribe to AppConfig.schedule events.
Fires each time a schedule event activates or deactivates tracking.
Check state.enabled in your callback to determine whether tracking
was started or stopped.
const subscription = BackgroundGeolocation.onSchedule((state) => {
if (state.enabled) {
console.log("[onSchedule] scheduled start tracking");
} else {
console.log("[onSchedule] scheduled stop tracking");
}
});
schedule
Methods¶
changePace¶
changePace(isMoving: boolean): Promise<State>;
Manually toggle the SDK's motion state between stationary and moving.
Passing true immediately engages location services and begins tracking,
bypassing stationary monitoring. Passing false turns off location
services and returns the SDK to the stationary state.
Use this in workout-style apps where you want explicit start/stop control independent of the device's motion sensors.
BackgroundGeolocation.changePace(true); // location services ON ("moving")
BackgroundGeolocation.changePace(false); // location services OFF ("stationary")
destroyTransistorAuthorizationToken¶
destroyTransistorAuthorizationToken(url: string): Promise<void>;
Destroy a Transistor authorization token.
See TransistorAuthorizationService for more information.
findOrCreateTransistorAuthorizationToken¶
findOrCreateTransistorAuthorizationToken(orgname: string, username: string, url?: string): Promise<TransistorAuthorizationToken>;
Find or create a Transistor authorization token.
See TransistorAuthorizationService for more information.
getCurrentPosition¶
getCurrentPosition(options?:CurrentPositionRequest): Promise<Location>;
Retrieve the current Location.
Instructs the SDK to fetch a single location at maximum power and accuracy. The location is persisted to SQLite and posted to HttpConfig.url just like any other recorded location. If an error occurs, the promise rejects with a LocationError.
Options¶
Error Codes¶
See LocationError.
Note
The SDK requests multiple location samples internally to find the best
fix. All intermediate samples are delivered to onLocation with
Location.sample set to true. Filter these out if you are
manually posting locations to your server.
const location = await BackgroundGeolocation.getCurrentPosition({
timeout: 30, // 30 second timeout to fetch location
maximumAge: 5000, // Accept the last-known-location if not older than 5000 ms.
desiredAccuracy: 10, // Try to fetch a location with an accuracy of `10` meters.
samples: 3, // How many location samples to attempt.
extras: { // Custom meta-data.
"route_id": 123
}
});
getDeviceInfo¶
getDeviceInfo(): Promise<DeviceInfo>;
Returns device information.
getOdometer¶
Retrieve the current odometer reading in meters.
The SDK continuously accumulates distance traveled between recorded locations.
Warning
Odometer accuracy depends on location accuracy. Noisy or inaccurate locations introduce error into accumulated distance. Use LocationFilter.odometerAccuracyThreshold to filter low-accuracy samples from odometer calculations.
See also
- LocationFilter.odometerAccuracyThreshold
- resetOdometer / setOdometer
getState¶
Return the current State of the SDK, including all Config parameters.
const state = await BackgroundGeolocation.getState();
console.log("[state] ", state.enabled, state.trackingMode);
ready¶
ready(config:Config): Promise<State>;
Signal to the SDK that your app is launched and ready, supplying the default Config.
Call ready exactly once per app launch, before calling start.
The SDK applies your configuration, restores persisted state, and prepares
for tracking. On subsequent launches after first install, it loads the
persisted configuration and merges your supplied Config on top.
See Config.reset for finer control over this behaviour.
Warning
Call ready once per app launch from your application root — not inside a
component or behind a UI action. On iOS, the OS can relaunch your app in
the background when the device starts moving; if ready is not called in
that path, tracking will not resume.
See also
- Config.reset
- setConfig
const state = await BackgroundGeolocation.ready({
geolocation: {
desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High,
distanceFilter: 10,
},
app: {
stopOnTerminate: false,
startOnBoot: true,
},
http: {
url: "http://your.server.com",
headers: { "my-auth-token": "secret-token" },
}
});
console.log("[ready] success", state);
BackgroundGeolocation.reset();
// Reset to documented default-values with overrides
bgGeo.reset({
distanceFilter: 10
});
registerHeadlessTask¶
registerHeadlessTask(callback: (event:HeadlessEvent) => Promise<void>): void;
Android only Registers a headless-task callback for Android background events when the
app has been terminated with AppConfig.stopOnTerminate:false.
The callback receives a HeadlessEvent with a name (event name)
and params (event data).
Warning
You must call registerHeadlessTask in your application root file (e.g.
index.js), not inside a component or behind a UI action.
Warning
Your function must be declared async. Await all work inside it — the
headless task is automatically terminated after the last line executes.
Note
Javascript headless callbacks are not supported by Cordova or Capacitor.
Debugging¶
While implementing your headless task, observe Android logs via:
See also - 📘 Android Headless Mode - AppConfig.enableHeadless
const BackgroundGeolocationHeadlessTask = async (event) => {
const params = event.params;
console.log("[BackgroundGeolocation HeadlessTask] -", event.name, params);
switch (event.name) {
case "terminate":
// Use await for async tasks
const location = await BackgroundGeolocation.getCurrentPosition({
samples: 1,
persist: false
});
console.log("[BackgroundGeolocation HeadlessTask] - getCurrentPosition:", location);
break;
}
// You must await all work you do in your task.
// Headless-tasks are automatically terminated after executing the last line.
await doWork();
}
BackgroundGeolocation.registerHeadlessTask(BackgroundGeolocationHeadlessTask);
removeListeners¶
Remove all event listeners.
Calls Subscription.remove on all active subscriptions.
reset¶
reset(config:Config): Promise<State>;
Reset the SDK configuration to documented default values.
If an optional Config is provided, it is applied after the reset.
BackgroundGeolocation.reset();
// Reset to default values with overrides
BackgroundGeolocation.reset({
geolocation: { distanceFilter: 10 }
});
resetOdometer¶
Reset the odometer to 0.
Internally performs a getCurrentPosition to record the exact
location where the odometer was reset. Equivalent to
.setOdometer(0).
const location = await BackgroundGeolocation.resetOdometer();
console.log("[resetOdometer] reset at: ", location);
setConfig¶
setConfig(config: Partial<Config>): Promise<State>;
Update the SDK's Config at runtime.
The supplied Config is merged into the current configuration and
applied immediately. Use this after ready has been called to
change settings dynamically.
const state = await BackgroundGeolocation.setConfig({
geolocation: {
desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High,
distanceFilter: 100.0,
},
app: {
stopOnTerminate: false,
startOnBoot: true,
},
});
console.log("[setConfig] success: ", state);
setOdometer¶
Set the odometer to an arbitrary value.
Internally performs a getCurrentPosition to record the exact
location where the odometer was set.
const location = await BackgroundGeolocation.setOdometer(1234.56);
console.log("[setOdometer] set at: ", location);
start¶
start(): Promise<State>;
Enable location and geofence tracking.
This is the SDK's power ON switch. The SDK enters its stationary state, acquires an initial location, then turns off location services until motion is detected. On Android, the Activity Recognition System monitors for motion; on iOS, a stationary geofence is created around the current location.
Note
If a AppConfig.schedule is configured, start overrides the
schedule and begins tracking immediately.
See also
- stop
- startGeofences
startGeofences¶
startGeofences(): Promise<State>;
Switch to geofences-only tracking mode.
In this mode no active location tracking occurs — only geofences are
monitored. Use the usual stop method to exit geofences-only mode.
start and startGeofences are mutually exclusive — call one or the
other, never both. start enables full tracking: location recording and
geofence monitoring run together. startGeofences enables geofence monitoring
only, with no continuous location recording. Calling start while already
in geofences-only mode (or vice versa) switches modes; there is no need to call
stop first.
See also
- stop
- 📘 Geofencing Guide
// Add a geofence.
BackgroundGeolocation.addGeofence({
notifyOnExit: true,
radius: 200,
identifier: "ZONE_OF_INTEREST",
latitude: 37.234232,
longitude: 42.234234
});
// Listen to geofence events.
BackgroundGeolocation.onGeofence((event) => {
console.log("[onGeofence] - ", event);
});
// Configure and start in geofences-only mode.
BackgroundGeolocation.ready({
http: { url: "http://my.server.com", autoSync: true }
}).then((state) => {
BackgroundGeolocation.startGeofences();
});
startSchedule¶
Activate the configured AppConfig.schedule.
Initiates the schedule defined in AppConfig.schedule. The SDK
automatically starts or stops tracking according to the schedule. To halt
scheduled tracking, call stopSchedule.
See also
- AppConfig.schedule
- stopSchedule
const state = await BackgroundGeolocation.startSchedule();
console.log("[startSchedule] success: ", state);
stop¶
stop(): Promise<State>;
Disable location and geofence monitoring.
This is the SDK's power OFF switch.
Note
If a AppConfig.schedule is configured, stop does not halt
the scheduler. Call stopSchedule explicitly if you also want to
stop scheduled tracking (for example, on user logout).
// Later when you want to stop the Scheduler (eg: user logout)
BackgroundGeolocation.stopSchedule();
Stop tracking and the scheduler¶
// Later when you want to stop the Scheduler (eg: user logout)
BackgroundGeolocation.stopSchedule();
stopSchedule¶
Halt scheduled tracking.
Warning
stopSchedule does not call stop if the SDK is currently
tracking. Call stop explicitly if you also want to end the current
tracking session.
See also
- startSchedule
// Later when you want to stop the Scheduler (eg: user logout)
await BackgroundGeolocation.stopSchedule();
const state = await BackgroundGeolocation.getState();
if (state.enabled) {
BackgroundGeolocation.stop();
}
Stop the scheduler and active tracking¶
// Later when you want to stop the Scheduler (eg: user logout)
await BackgroundGeolocation.stopSchedule();
const state = await BackgroundGeolocation.getState();
if (state.enabled) {
BackgroundGeolocation.stop();
}
watchPosition¶
watchPosition(options:WatchPositionRequest, locationCallback: (location:Location) => void, errorCallback?: (errorCode: number) => void):Subscription;
Start a continuous stream of location updates.
Each location is persisted to SQLite (when the SDK is State.enabled) and posted to HttpConfig.url if HTTP is configured. Returns a Subscription that must be retained to halt the stream.
Warning
watchPosition is designed for foreground use only — not for long-term
background monitoring. The SDK's motion-based tracking model does not
require it.
iOS¶
watchPosition continues running in the background, preventing iOS from
suspending your app. Remove the subscription in your app's suspend handler
to avoid draining the battery.
onResume() async {
// Start watching position while app in foreground, retaining the return Subscription.
this.watchPositionSubscription = await BackgroundGeolocation.watchPosition({
interval: 1000,
extras: {foo: "bar"}
}, (location) => {
console.log("[watchPosition] -", location);
}, (errorCode) => {
console.log("[watchPosition] ERROR -", errorCode);
});
}
onSuspend() {
// Halt watching position when app goes to background.
this.watchPositionSubscription.remove();
this.watchPositionSubscription = null;
}
Geofencing¶
addGeofence¶
addGeofence(geofence:Geofence): Promise<boolean>;
Add a Geofence to be monitored by the native geofencing API.
Note
If a geofence with the same Geofence.identifier already exists,
it is deleted before the new one is inserted. When adding multiple
geofences, addGeofences is approximately 10× faster.
See also
- 📘 Geofencing Guide
BackgroundGeolocation.addGeofence({
identifier: "Home",
radius: 150,
latitude: 45.51921926,
longitude: -73.61678581,
notifyOnEntry: true,
notifyOnExit: false,
notifyOnDwell: true,
loiteringDelay: 30000, // 30 seconds
extras: { // Optional arbitrary meta-data
zone_id: 1234
}
}).then((success) => {
console.log("[addGeofence] success");
}).catch((error) => {
console.log("[addGeofence] FAILURE: ", error);
});
addGeofences¶
addGeofences(geofences:Geofence[]): Promise<boolean>;
Add a list of Geofence to be monitored by the native geofencing API.
Note
If any geofence already exists with a matching Geofence.identifier, it is deleted before the new one is inserted.
See also
- 📘 Geofencing Guide
- addGeofence
const geofences = [{
identifier: "foo",
radius: 200,
latitude: 45.51921926,
longitude: -73.61678581,
notifyOnEntry: true
}, {
identifier: "bar",
radius: 200,
latitude: 45.51921926,
longitude: -73.61678581,
notifyOnEntry: true
}];
BackgroundGeolocation.addGeofences(geofences);
geofenceExists¶
Determine whether a geofence with the given identifier exists in the SDK's database.
See also
- 📘 Geofencing Guide
const exists = await BackgroundGeolocation.geofenceExists("HOME");
console.log("[geofenceExists] ", exists);
getGeofence¶
getGeofence(identifier: string): Promise<Geofence>;
Fetch a single Geofence by identifier from the SDK's database.
See also
- 📘 Geofencing Guide
const geofence = await BackgroundGeolocation.getGeofence("HOME");
console.log("[getGeofence] ", geofence);
getGeofences¶
getGeofences(): Promise<Geofence[]>;
Fetch all Geofence records from the SDK's database.
Returns an empty array if no geofences are stored.
See also
- 📘 Geofencing Guide
const geofences = await BackgroundGeolocation.getGeofences();
console.log("[getGeofences]: ", geofences);
removeGeofence¶
removeGeofence(identifier: string): Promise<boolean>;
Remove the Geofence with the given Geofence.identifier.
See also
- 📘 Geofencing Guide
BackgroundGeolocation.removeGeofence("Home").then((success) => {
console.log("[removeGeofence] success");
}).catch((error) => {
console.log("[removeGeofence] FAILURE: ", error);
});
removeGeofences¶
Remove all monitored Geofence records, or a specific subset by identifier.
See also
- 📘 Geofencing Guide
Data Management¶
destroyLocation¶
destroyLocation(uuid: string): Promise<void>;
Remove a single location by Location.uuid.
destroyLocations¶
Remove all records from the SDK's SQLite database.
getCount¶
Retrieve the count of all locations currently stored in the SDK's SQLite database.
getLocations¶
Retrieve all Location records stored in the SDK's SQLite database.
sync¶
Manually upload all queued locations to HttpConfig.url.
Initiates a POST of all records in the SQLite database to your configured
HttpConfig.url. Records that receive a 200 OK response are
deleted from the database. If HttpConfig.batchSync is true, all
locations are sent in a single request; otherwise one request is made per
location. If no HTTP service is configured, all records are deleted from
the database.
See also
- HTTP Guide
Authorization¶
getProviderState¶
getProviderState(): Promise<ProviderChangeEvent>;
Retrieve the current location-services authorization state.
See also
- onProviderChange to subscribe to future authorization changes.
const providerState = await BackgroundGeolocation.getProviderState();
console.log("- Provider state: ", providerState);
requestPermission¶
requestPermission(): Promise<AuthorizationStatus>;
Manually request location permission using the configured GeoConfig.locationAuthorizationRequest.
Resolves successfully if either WhenInUse or Always is granted,
regardless of the requested level. Rejects if the user denies.
If permission is already granted, resolves immediately. If iOS has already shown the authorization dialog and the current grant does not match the configured request, the SDK presents an alert offering to direct the user to your app's Settings page.
Note
The SDK automatically requests permission when you call start,
startGeofences, or getCurrentPosition. You do not need to
call this method in typical use.
See also
- GeoConfig.locationAuthorizationRequest
- GeoConfig.disableLocationAuthorizationAlert
- GeoConfig.locationAuthorizationAlert
- AppConfig.backgroundPermissionRationale (Android)
- requestTemporaryFullAccuracy (iOS 14+)
BackgroundGeolocation.onProviderChange((event) => {
console.log('[providerchange]', event);
});
const state = await BackgroundGeolocation.ready({
geolocation: { locationAuthorizationRequest: 'Always' }
});
try {
const status = await BackgroundGeolocation.requestPermission();
console.log('[requestPermission] success: ', status);
} catch (status) {
console.warn('[requestPermission] FAILURE: ', status);
}
requestTemporaryFullAccuracy¶
requestTemporaryFullAccuracy(purposeKey: string): Promise<AccuracyAuthorization>;
Request temporary full-accuracy location authorization. [iOS 14+]
iOS 14 allows users to grant only reduced location accuracy. This method
presents the system dialog
(requestTemporaryFullAccuracyAuthorization)
requesting full accuracy for the lifetime of the current app session.

Configuration — Info.plist¶
Add the Privacy - Location Temporary Usage Description Dictionary key
to your Info.plist:

The dictionary keys (e.g. Delivery) are passed as purposeKey. The
corresponding value is the message shown to the user explaining the
purpose of your request.
The dialog fails to present if:
- The Info.plist entry for purposeKey is missing.
- The app is already authorized for full accuracy.
- The app is in the background.
Note
On Android and iOS versions below 14, this method returns AccuracyAuthorization.Full immediately without presenting a dialog.
See also - ProviderChangeEvent.accuracyAuthorization
BackgroundGeolocation.onProviderChange((event) => {
if (event.accuracyAuthorization == BackgroundGeolocation.AccuracyAuthorization.Reduced) {
// Supply "Purpose" key from Info.plist as 1st argument.
BackgroundGeolocation.requestTemporaryFullAccuracy("Delivery").then((accuracyAuthorization) => {
if (accuracyAuthorization == BackgroundGeolocation.AccuracyAuthorization.Full) {
console.log('[requestTemporaryFullAccuracy] GRANTED: ', accuracyAuthorization);
} else {
console.log('[requestTemporaryFullAccuracy] DENIED: ', accuracyAuthorization);
}
}).catch((error) => {
console.warn("[requestTemporaryFullAccuracy] FAILED TO SHOW DIALOG: ", error);
});
}
});
Background Tasks¶
startBackgroundTask¶
Signal to the OS that you need to perform a long-running task.
The OS keeps the app running in the background until you signal completion
with stopBackgroundTask. Your callback receives a taskId which
you must pass to stopBackgroundTask when finished — always call it,
even if an error occurs, to avoid hanging the background task.
iOS¶
Uses beginBackgroundTaskWithExpirationHandler.
iOS provides exactly 180 seconds of background time. The SDK
automatically stops the task before the OS force-kills the app.
✅-[BackgroundTaskManager createBackgroundTask] 1
✅-[BackgroundTaskManager stopBackgroundTask:]_block_invoke 1 OF (1)
Android¶
Uses WorkManager.
The SDK imposes a 3-minute limit before automatically force-killing
the task.
I TSLocationManager: [c.t.l.u.BackgroundTaskManager onStartJob] ⏳ startBackgroundTask: 6
I TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] ⏳ stopBackgroundTask: 6
onLocation(location) {
console.log("[location] ", location);
// Perform some long-running task (eg: HTTP request)
BackgroundGeolocation.startBackgroundTask().then((taskId) => {
performLongRunningTask().then(() => {
// When your long-running task is complete, signal completion of taskId.
BackgroundGeolocation.stopBackgroundTask(taskId);
}).catch((error) => {
// Be sure to catch errors: never leave your background-task hanging.
console.error(error);
BackgroundGeolocation.stopBackgroundTask(taskId);
});
});
}
stopBackgroundTask¶
Signal completion of a startBackgroundTask to the OS.
The OS may now suspend the app if appropriate.
BackgroundGeolocation.startBackgroundTask().then((taskId) => {
// Perform some long-running task (eg: HTTP request)
performLongRunningTask().then(() => {
// When your long-running task is complete, signal completion of taskId.
BackgroundGeolocation.stopBackgroundTask(taskId);
});
});
Logging¶
playSound¶
Play a system sound.
iOS¶
Provide a numeric SystemSoundID.
Android¶
Provide a sound name string.
setLogLevel¶
setLogLevel(level:LogLevel): Promise<void>;
Sets the LoggerConfig.logLevel.
Device¶
getSensors¶
getSensors(): Promise<Sensors>;
Returns the availability of motion sensors: accelerometer, gyroscope, and magnetometer.
These sensors power the motion activity-recognition system. When any sensor is absent (particularly on low-end Android devices), motion recognition performance degrades significantly.
isPowerSaveMode¶
Returns the current state of the operating system's power-saving mode.
Power-saving mode can throttle background services such as GPS and HTTP uploads.
See also
- onPowerSaveChange to subscribe to future changes.
iOS¶
Power Saving mode is enabled manually in Settings → Battery or via an automatic OS prompt.

Android¶
Battery Saver is enabled manually in Settings → Battery → Battery Saver or automatically when the battery drops below a configured threshold.

Properties¶
AccuracyAuthorization¶
AccuracyAuthorization: object;
Enum namespace indicating whether the user granted full or reduced location accuracy. [iOS 14+]
Used by ProviderChangeEvent.accuracyAuthorization and
requestTemporaryFullAccuracy.
BackgroundGeolocation.onProviderChange((event) => {
if (event.accuracyAuthorization ===
BackgroundGeolocation.AccuracyAuthorization.Reduced) {
// Handle reduced-accuracy case
}
});
ActivityType¶
ActivityType: object;
iOS only Enum namespace specifying the type of user activity (AutomotiveNavigation, Fitness, OtherNavigation, etc).
Used by GeoConfig.activityType.
AuthorizationStatus¶
AuthorizationStatus: object;
Enum namespace representing the OS-level authorization state for location services (Denied, Restricted, Always, WhenInUse).
Returned from requestPermission() and onProviderChange.
const status = await BackgroundGeolocation.requestPermission();
if (status === BackgroundGeolocation.AuthorizationStatus.Always) {
// Good to start tracking
}
AuthorizationStrategy¶
AuthorizationStrategy: object;
Enum namespace defining how the HTTP service performs authorization.
Includes basic, JWT, and custom strategies. Used by AuthorizationConfig.strategy.
BackgroundGeolocation.ready({
authorization: {
strategy: BackgroundGeolocation.AuthorizationStrategy.Jwt
}
});
DesiredAccuracy¶
DesiredAccuracy: object;
Enum namespace controlling the native location engine's target accuracy.
Higher accuracy consumes more battery. Used by GeoConfig.desiredAccuracy.
BackgroundGeolocation.ready({
geolocation: {
desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High
}
});
Event¶
Event: object;
Enum namespace of all event names emitted by the SDK
(location, geofence, motionchange, heartbeat, etc).
HttpMethod¶
HttpMethod: object;
Enum namespace defining the HTTP method used for location uploads (POST, PUT, etc).
Used by HttpConfig.method.
KalmanProfile¶
KalmanProfile: object;
Enum namespace selecting a preset Kalman filter tuning profile (aggressive, moderate, or relaxed smoothing).
Used by LocationFilter.kalmanProfile.
BackgroundGeolocation.ready({
geolocation: {
filter: {
kalmanProfile: BackgroundGeolocation.KalmanProfile.Aggressive
}
}
});
LocationFilterPolicy¶
LocationFilterPolicy: object;
Enum namespace selecting the filtering engine policy for noise-reduction and smoothing.
Used by LocationFilter.policy.
BackgroundGeolocation.ready({
geolocation: {
filter: {
policy: BackgroundGeolocation.LocationFilterPolicy.Adjust
}
}
});
LocationRequest¶
LocationRequest: object;
iOS only Enum namespace defining the type of location permission request
(Always, WhenInUse, or Any). Used by GeoConfig.locationAuthorizationRequest.
BackgroundGeolocation.ready({
geolocation: {
locationAuthorizationRequest: BackgroundGeolocation.LocationRequest.Always
}
});
LogLevel¶
LogLevel: object;
Enum namespace controlling verbosity of the SDK logger.
Used by LoggerConfig.logLevel. Values range from silent (Off) to
extremely verbose (Verbose).
NotificationPriority¶
NotificationPriority: object;
Android only Enum namespace controlling Android foreground-service notification priority and icon placement (top, bottom, hidden).
Used by NotificationConfig.priority.
BackgroundGeolocation.ready({
app: {
notification: {
priority: BackgroundGeolocation.NotificationPriority.High
}
}
});
PersistMode¶
PersistMode: object;
Enum namespace controlling which records the SDK persists to SQLite: locations only, geofences only, both, or none.
Used by PersistenceConfig.persistMode.
BackgroundGeolocation.ready({
persistence: {
persistMode: BackgroundGeolocation.PersistMode.All
}
});
TriggerActivity¶
TriggerActivity: object;
Enum namespace defining which physical motion activities can trigger motion-detection transitions (still → moving).
Used by ActivityConfig.triggerActivities.
BackgroundGeolocation.ready({
activity: {
triggerActivities: [
BackgroundGeolocation.TriggerActivity.InVehicle
]
}
});
deviceSettings¶
deviceSettings:DeviceSettings;
DeviceSettings API
logger¶
logger:Logger;
Logger API