Subscribe to changes in motion activity.
Your callback
will be executed each time the activity-recognition system receives an event (still, on_foot, in_vehicle, on_bicycle, running
).
Android MotionActivityEvent.confidence always reports 100
%.
Subscribe to changes in network connectivity.
Fired when the state of the device's network-connectivity changes (enabled -> disabled and vice-versa). By default, the plugin will automatically fire
a connectivitychange
event with the current state network-connectivity whenever the start method is executed.
âšī¸ The SDK subscribes internally to connectivitychange
events — if you've configured the SDK's HTTP Service (See HTTP Guide) and your app has queued locations,
the SDK will automatically initiate uploading to your configured Config.url when network connectivity is detected.
Subscribe to changes in plugin State.enabled.
Fired when the SDK's State.enabled changes. For example, executing start and stop will cause the onEnabledChnage
event to fire.
This event is primarily designed for use with the configuration option stopAfterElapsedMinutes, which automatically executes the SDK's
stop method.
Subscribe to Geofence transition events.
Your supplied callback
will be called when any monitored geofence crossing occurs.
Subscribe to changes in actively monitored geofences.
Fired when the list of monitored-geofences changed. The BackgroundGeolocation SDK contains powerful geofencing features that allow you to monitor any number of circular geofences you wish (thousands even), in spite of limits imposed by the native platform APIs (20 for iOS; 100 for Android).
The plugin achieves this by storing your geofences in its database, using a geospatial query to determine those geofences in proximity (@see geofenceProximityRadius), activating only those geofences closest to the device's current location (according to limit imposed by the corresponding platform).
When the device is determined to be moving, the plugin periodically queries for geofences in proximity (eg. every minute) using the latest recorded location. This geospatial query is very fast, even with tens-of-thousands geofences in the database.
It's when this list of monitored geofences changes, that the plugin will fire the onGeofencesChange
event.
Subscribe to periodic heartbeat events.
Your callback
will be executed for each heartbeatInterval while the device is in stationary state (iOS requires preventSuspend: true as well).
Subscribe to HTTP responses from your server Config.url.
Subscribe to location events.
Every location recorded by the SDK is provided to your callback
, including those from onMotionChange, getCurrentPosition and watchPosition.
Subscribe to motionchange
events.
Your callback
will be executed each time the device has changed-state between MOVING or STATIONARY.
Subscribe to state changes in OS power-saving system.
Fired when the state of the operating-system's "Power Saving" mode changes. Your callback
will be provided with a bool
showing whether
"Power Saving" is enabled or disabled. Power Saving mode can throttle certain services in the background, such as HTTP requests or GPS.
Subscribe to changes in device's location-services configuration / authorization.
Your callback
fill be executed whenever a change in the state of the device's Location Services has been detected. eg: "GPS ON", "WiFi only".
Subscribe to schedule events.
Your callback
will be executed each time a schedule event fires. Your callback
will be provided with the current State: state.enabled
will reflect the state according to your schedule.
DeviceSettings API
Provides an API to show Android & vendor-specific Battery / Power Management settings screens that can affect performance of the Background Geolocation SDK on various devices.
The site Don't Kill My App provides a comprehensive list of poor Android vendors which throttle background-services that this plugin relies upon.
This DeviceSettings API is an attempt to provide resources to direct the user to the appropriate vendor-specific settings screen to resolve issues with background operation.
Logger API
Manually toggles the SDK's motion state between stationary and moving.
When provided a value of true
, the plugin will engage location-services and begin aggressively tracking the device's location immediately,
bypassing stationary monitoring.
If you were making a "Jogging" application, this would be your [Start Workout]
button to immediately begin location-tracking. Send false
to turn off location-services and return the plugin to the stationary state.
Destroy a single location by Location.uuid
Remove all records in SDK's SQLite database.
Destroys the cached Transistor JSON Web Token used to authorize with the Demo Server at http://tracker.transistorsoft.com or your local instance of background-geolocation-console
Returns a JSON Web Token (JWT) suitable for Authorization with the Transistor Software demo server at http://tracker.transistorsoft.com.
To learn how to upload locations to the Transistor Demo Server, see TransistorAuthorizationToken.
This token is typically provided to Config.transistorAuthorizationToken when first configuring the SDK with ready.
@param {String} orgname
Represents a "company" or "organization"; a container for posting locations from multiple devices to the same account. orgname
is used for accessing your device results in web app, eg: http://tracker.transistorsoft.com/my-organization-name.
@param {String} username
Appended to the DeviceInfo.model as a means of creating a consistent and unique device identifier. For example:
Pixel 3a-my-username
A310-my-username
iPhone 11,3-my-username
@param {String} url [http://tracker.transistorsoft.com]
The server to register with and receive authentication tokens from. Defaults to http://tracker.transistorsoft.com
. If you have a local instance of background-geolocation-console running
on your localhost, you would provide the ip address of your server, eg: http://192.168.0.100:9000
.
When the SDK receives the TransistorAuthorizationToken from url
, it will be cached in persistant-storage within the native code. If the SDK doesn"t find a cached token on the client, it will automatically register for one from url
, using the provided orgname
and username
. Otherwise, the cached token will be immediately returned.
Determine if a particular geofence exists in the SDK's database.
Retrieve the count of all locations current stored in the SDK's SQLite database.
Retrieves the current Location.
This method instructs the native code to fetch exactly one location using maximum power & accuracy. The native code will persist the fetched location to
its SQLite database just as any other location in addition to POSTing to your configured Config.url.
If an error occurs while fetching the location, catch
will be provided with an LocationError.
Fetch a list of all Geofence in the SDK's database. If there are no geofences being monitored, you'll receive an empty Array
.
Retrieve a List of Location currently stored in the SDK's SQLite database.
Retrieve the current distance-traveled ("odometer").
The plugin constantly tracks distance traveled, computing the distance between the current location and last and maintaining the sum. To fetch the current odometer reading:
Retrieves the current state of location-provider authorization.
Fetches the state of the operating-system's "Power Saving" mode.
Subscribe to Authorization events.
Fired when Authorization.refreshUrl responds, either successfully or not. If successful, AuthorizationEvent.success will be true
and AuthorizationEvent.response will
contain the decoded JSON response returned from the server.
If authorization failed, AuthorizationEvent.error will contain the error message.
[Android-only] Subscribe to button-clicks of a custom Notification.layout on the Android foreground-service notification.
Signal to the plugin that your app is launched and ready, proving the default Config.
The supplied Config will be applied only at first install of your app â for every launch thereafter, the plugin will automatically load its last-known configuration from persistent storage. The plugin always remembers the configuration you apply to it.
Registers a Javascript callback to execute in the Android "Headless" state, where the app has been terminated configured with
stopOnTerminate:false
. * The received event
object contains a name
(the event name) and params
(the event data-object).
registerHeadlessTask
in your application root file (eg: index.js
).Alias for removeListeners
Removes a Geofence having the given Geofence.identifier.
Destroy all Geofence
Removes all event-listeners.
Calls Subscription.remove on all subscriptions.
Manually request location permission from the user with the configured Config.locationAuthorizationRequest.
The method will resolve successful if either WhenInUse
or Always
is authorized, regardless of Config.locationAuthorizationRequest. Otherwise an error will be returned (eg: user denies location permission).
If the user has already provided authorization for location-services, the method will resolve successfully immediately.
If iOS has already presented the location authorization dialog and the user has not currently authorized your desired Config.locationAuthorizationRequest, the SDK will present an error dialog offering to direct the user to your app's Settings screen.
[iOS 14+]
iOS 14 has introduced a new [Precise: On]
switch on the location authorization dialog allowing users to disable high-accuracy location.
The method requestTemporaryFullAccuracy
(Apple docs) will allow you to present a dialog to the user requesting temporary full accuracy for the lifetime of this application run (until terminate).
Info.plist
In order to use this method, you must configure your Info.plist
with the Dictionary
key:
Privacy - Location Temporary Usage Description Dictionary
The keys of this Dictionary
(eg: Delivery
) are supplied as the first argument to the method. The value
will be printed on the dialog shown to the user, explaing the purpose of your request for full accuracy.
If the dialog fails to be presented, an error will be thrown:
Note: Android and older versions of iOS < 14
will return BackgroundGeolocation.ACCURACY_AUTHORIZATION_FULL.
Resets the plugin configuration to documented default-values.
If an optional Config is provided, it will be applied after the configuration reset.
Initialize the odometer
to 0
.
Re-configure the SDK's Config parameters. This is the method to use when you wish to change the plugin Config after ready has been executed.
The supplied Config will be appended to the current configuration and applied in realtime.
Enable location + geofence tracking.
This is the SDK's power ON button. The plugin will initially start into its stationary state, fetching an initial location before turning off location services. Android will be monitoring its Activity Recognition System while iOS will create a stationary geofence around the current location.
If you've configured a schedule, this method will override that schedule and engage tracking immediately.
Sends a signal to OS that you wish to perform a long-running task.
The OS will keep your running in the background and not suspend it until you signal completion with the stopBackgroundTask method. Your callback will be provided with a single parameter taskId
which you will send to the stopBackgroundTask method.
Engages the geofences-only State.trackingMode.
In this mode, no active location-tracking will occur — only geofences will be monitored. To stop monitoring "geofences" TrackingMode, simply use the usual stop method.
Initiate the configured schedule.
If a schedule was configured, this method will initiate that schedule. The plugin will automatically be started or stopped according to the configured schedule.
To halt scheduled tracking, use stopSchedule.
Signal completion of startBackgroundTask
Sends a signal to the native OS that your long-running task, addressed by taskId
provided by startBackgroundTask is complete and the OS may proceed
to suspend your application if applicable.
Stop watch-position updates initiated from watchPosition.
Manually execute upload to configured Config.url
If the plugin is configured for HTTP with an Config.url and autoSync false
, the sync method will initiate POSTing the locations
currently stored in the native SQLite database to your configured Config.url. When your HTTP server returns a response of 200 OK
, that record(s)
in the database will be DELETED.
If you configured batchSync true
, all the locations will be sent to your server in a single HTTP POST request, otherwise the plugin will
execute an HTTP post for each Location in the database (REST-style). Your callback will be executed and provided with a List
of all the
locations from the SQLite database. If you configured the plugin for HTTP (by configuring a Config.url, your callback will be executed after all
the HTTP request(s) have completed. If the plugin failed to sync to your server (possibly because of no network connection), the failure callback will
be called with an error message. If you are not using the HTTP features, sync will delete all records from its SQLite database.
Start a stream of continuous location-updates. The native code will persist the fetched location to its SQLite database just as any other location (If the SDK is currently State.enabled) in addition to POSTing to your configured Config.url (if you've enabled the HTTP features).
watchPosition
is not recommended for long term monitoring in the background — It's primarily designed for use in the foreground only. You might use it for fast-updates of the user's current position on the map, for example.
The SDK's primary Philosophy of Operation does not require watchPosition
.
watchPosition
will continue to run in the background, preventing iOS from suspending your application. Take care to listen to suspend
event and call stopWatchPosition if you don't want your app to keep running in the background, consuming battery.
Generated using TypeDoc
Primary API of the SDK.
đ Help
âĄī¸ Events
BackgroundGeolocation is event-based. Interacting with the SDK is largely through implementing listeners on the following events:
ENTER, EXIT, DWELL
).đ§ Config API
BackgroundGeolocation is highly configurable. See the Config API for more information.
There are three main steps to using
BackgroundGeolocation
â ī¸ Warning:
Do not execute any API method which will require accessing location-services until the callback to ready executes (eg: getCurrentPosition, watchPosition, start).
Promise API
The
BackgroundGeolocation
Javascript API supports Promises for nearly every method (the exceptions are watchPosition and adding event-listeners via#onEventName
methods.)