πŸ”§ Configuration API.

The following configuration options are used to configure the SDK via the methods BackgroundGeolocation.ready and BackgroundGeolocation.setConfig.

example
BackgroundGeolocation.ready({
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
  distanceFilter: 10,
  stopOnTerminate: false,
  startOnBoot: true,
  url: 'http://my.server.com',
  params: {
    "user_id": 123
  },
  headers: {
    "my-auth-token":"secret-key"
  }
}).then((state) => {
  console.log('[ready] BackgroundGeolocation is configured and ready to use');

  BackgroundGeolocation.start();
})

// Or with #setConfig
BackgroundGeolocation.setConfig({
  extras: {route_id: 1234},
  url: 'https://my.new.server.com'
})

Geolocation Options

[Geolocation] Common Options

Option Type Note
desiredAccuracy LocationAccuracy Default: BackgroundGeolocation.DESIRED_ACCURACY_HIGH. Specify the desired-accuracy of the geolocation system.
distanceFilter Integer Default: 10. The minimum distance (measured in meters) a device must move horizontally before an update event is generated.
disableElasticity Boolean Default: false. Set true to disable automatic speed-based distanceFilter elasticity. eg: When device is moving at highway speeds, locations are returned at ~ 1 / km.
elasticityMultiplier Float Default: 1. Controls the scale of automatic speed-based distanceFilter elasticity. Increasing elasticityMultiplier will result in few location samples as speed increases.
stopAfterElapsedMinutes Integer Default: 0. The plugin can optionally automatically stop tracking after some number of minutes elapses after the BackgroundGeolocation.start method was called.
stopOnStationary Boolean Default: false. The plugin can optionally automatically stop tracking when the stopTimeout timer elapses.
desiredOdometerAccuracy Integer Default: 100. Location accuracy threshold in meters for odometer calculations.

[Geolocation] iOS Options

Option Type Note
stationaryRadius Integer Default: 25. When stopped, the minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage.
useSignificantChangesOnly Boolean Default: false. Defaults to false. Set true in order to disable constant background-tracking and use only the iOS Significant Changes API.
locationAuthorizationRequest LocationAuthorizationRequest Default: Always. The desired iOS location-authorization request, either Always, WhenInUse or Any.
locationAuthorizationAlert Object When you configure the plugin locationAuthorizationRequest Always or WhenInUse and the user changes that value in the app's location-services settings or disables location-services, the plugin will display an Alert directing the user to the Settings screen.
disableLocationAuthorizationAlert Boolean Default: false. Disables automatic authorization alert when plugin detects the user has disabled location authorization. You will be responsible for handling disabled location authorization by listening to the providerchange event.

[Geolocation] Android Options

Option Type Note
locationUpdateInterval Integer Default: 1000. With distanceFilter: 0, Sets the desired interval for location updates, in milliseconds. ⚠️ This setting will be ignored when distanceFilter > 0
fastestLocationUpdateInterval Integer Default: 10000. Explicitly set the fastest interval for location updates, in milliseconds.
deferTime Integer Default: 0. Sets the maximum wait time in milliseconds for location updates to be delivered to your callback, when they will all be delivered in a batch.
allowIdenticalLocations Boolean Default: false. The Android plugin will ignore a received location when it is identical to the last location. Set true to override this behaviour and record every location, regardless if it is identical to the last location.

Activity Recognition Options

[Activity Recognition] Common Options

Option Type Note
activityRecognitionInterval Integer Default: 10000. The desired time between activity detections. Larger values will result in fewer activity detections while improving battery life. A value of 0 will result in activity detections at the fastest possible rate.
stopTimeout Integer Default: 5. The number of minutes to wait before turning off location-services after the ActivityRecognition System (ARS) detects the device is STILL
minimumActivityRecognitionConfidence Integer Default: 75. Each activity-recognition-result returned by the API is tagged with a "confidence" level expressed as a %. You can set your desired confidence to trigger a state-change.
stopDetectionDelay Integer Default: 0. Number of minutes to delay the stop-detection system from being activated.
disableStopDetection Boolean Default: false. Disable accelerometer-based Stop-detection System. ⚠️ Not recommended

[Activity Recognition] iOS Options

Option Type Note
activityType ActivityType Default: BackgroundGeolocation.ACTIVITY_TYPE_OTHER. Presumably, this affects ios GPS algorithm. See Apple docs for more information
disableMotionActivityUpdates Boolean Default: false. Disable iOS motion-activity updates (eg: "walking", "in_vehicle"). This feature requires a device having the M7 co-processor (ie: iPhone 5s and up). ⚠️ The plugin is HIGHLY optimized to use this for improved battery performance. You are STRONLY recommended to NOT disable this.

HTTP & Persistence Options

Option Type Note
url String Default: undefined. Your server url where you wish to HTTP POST locations to
httpTimeout Integer Default: 60000. HTTP request timeout in milliseconds.
params Object Default: undefined. Optional HTTP params sent along in HTTP request to above url
extras Object Default: undefined. Optional meta-data to attach to each recorded location
headers Object Default: undefined. Optional HTTP headers sent along in HTTP request to above url
method String Default: POST. The HTTP method. Defaults to POST. Some servers require PUT.
httpRootProperty String Default: location. The root property of the JSON data where location-data will be appended.
locationTemplate String Default: undefined. Optional custom location data schema (eg: { "lat:<%= latitude %>, "lng":<%= longitude %> }
geofenceTemplate String Default: undefined. Optional custom geofence data schema (eg: { "lat:<%= latitude %>, "lng":<%= longitude %>, "geofence":"<%= geofence.identifier %>:<%= geofence.action %>" }
autoSync Boolean Default: true. If you've enabeld HTTP feature by configuring an url, the plugin will attempt to upload each location to your server as it is recorded.
autoSyncThreshold Integer Default: 0. The minimum number of persisted records to trigger an autoSync action.
batchSync Boolean Default: false. If you've enabled HTTP feature by configuring an url, batchSync: true will POST all the locations currently stored in native SQLite datbase to your server in a single HTTP POST request.
maxBatchSize Integer Default: -1. If you've enabled HTTP feature by configuring an url and batchSync: true, this parameter will limit the number of records attached to each batch.
maxDaysToPersist Integer Default: 1. Maximum number of days to store a geolocation in plugin's SQLite database.
maxRecordsToPersist Integer Default: -1. Maximum number of records to persist in plugin's SQLite database. Defaults to -1 (no limit). To disable persisting locations, set this to 0
locationsOrderDirection String Default: ASC. Controls the order that locations are selected from the database (and synced to your server). Defaults to ascending (ASC), where oldest locations are synced first. Descending (DESC) syncs latest locations first.

Application Options

[Application] Common Options

Option Type Note
stopOnTerminate Boolean Default: true. Set false to continue tracking after user teminates the app.
startOnBoot Boolean Default: false. Set to true to enable background-tracking after the device reboots.
heartbeatInterval Integer Default: 60. Rate in seconds to fire BackgroundGeolocation.onHeartbeat events.
schedule Array Default: undefined. Defines a schedule to automatically start/stop tracking at configured times

[Application] iOS Options

Option Type Note
preventSuspend Boolean Default: false. Enable this to prevent iOS from suspending your app in the background while in the stationary state. Must be used in conjunction with a heartbeatInterval.

[Application] Android Options

Option Type Note
foregroundService Boolean Default: false. Set true to make the plugin mostly immune to OS termination due to memory pressure from other apps.
enableHeadless Boolean Default: false. Set to true to enable "Headless" mode when the user terminates the application. In this mode, you can respond to all the plugin's events in the native Android environment. For more information, see the wiki for Android Headless Mode
notificationPriority NotificationPriority Default: NOTIFICATION_PRIORITY_DEFAULT. Controls the priority of the foregroundService notification and notification-bar icon.
notificationTitle String Default: Your App Name. When running the service with foregroundService: true, Android requires a persistent notification in the Notification Bar. Defaults to the application name
notificationText String Default: Location service activated. When running the service with foregroundService: true, Android requires a persistent notification in the Notification Bar.
notificationColor String Default: undefined. When running the service with foregroundService: true, controls the color of the persistent notification in the Notification Bar.
notificationSmallIcon String Default: Your App Icon. When running the service with foregroundService: true, controls your customize notification small icon. Defaults to your application icon.
notificationLargeIcon String Default: undefined. When running the service with foregroundService: true, controls your customize notification large icon. Defaults to undefined.
notificationChannelName String Default: app name. On Android O+, the plugin's foreground-service needs to create a "Notification Channel". The name of this channel can be seen in Settings->App & Notifications->Your App. Defaults to Your App.
forceReloadOnMotionChange Boolean Default: false. Launch your app whenever the BackgroundGeolocation.onMotionChange event fires.
forceReloadOnLocationChange Boolean Default: false. Launch your app whenever the BackgroundGeolocation.onLocation event fires.
forceReloadOnGeofence Boolean Default: false. Launch your app whenever the BackgroundGeolocation.onGeofence event fires.
forceReloadOnHeartbeat Boolean Default: false. Launch your app whenever the BackgroundGeolocation.onHeartbeat event fires.
forceReloadOnSchedule Boolean Default: false. Launch your app whenever a BackgroundGeolocation.onSchedule event fires.
forceReloadOnBoot Boolean Default: false. If the user reboots the device with the plugin configured for startOnBoot: true, your app will launch when the device is rebooted.

Geofencing Options

Option Type Note
geofenceProximityRadius Integer Default: 1000. Radius in meters to query for geofences within proximity.
geofenceInitialTriggerEntry Boolean Default: true. Set false to disable triggering a geofence immediately if device is already inside it.

Logging & Debug Options

Option Type Note
debug Boolean Default: false. When enabled, the plugin will emit sounds & notifications for life-cycle events of background-geolocation
logLevel Integer Default: LOG_LEVEL_VERBOSE. Sets the verbosity of the plugin's logs from LOG_LEVEL_OFF to LOG_LEVEL_VERBOSE
logMaxDays Integer Default: 3. Maximum days to persist a log-entry in database.

Hierarchy

Index

Properties

Optional activityRecognitionInterval

activityRecognitionInterval: number

Controls the sample-rate of the motion activity-recognition system.

break

Defaults to 10000 (10 seconds). This is primarily an Android option, since only Android can constantly monitor the activity-detection API in the background (iOS uses a "stationary geofence" to detect device-motion). The desired time between activity detections. Larger values will result in fewer activity detections while improving battery life. A value of 0 will result in activity detections at the fastest possible rate.

Optional activityType

activityType: ActivityType

[iOS only] Presumably, this affects iOS stop-detect algorithm. Apple is vague about what exactly this option does.

Available values are defined as constants upon the BackgroundGeolocation class.

Name
BackgroundGeolocation.ACTIVITY_TYPE_OTHER
BackgroundGeolocation.ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION
BackgroundGeolocation.ACTIVITY_TYPE_FITNESS
BackgroundGeolocation.ACTIVITY_TYPE_OTHER_NAVIGATION
example
BackgroundGeolocation.ready({
  activityType: BackgroundGeolocation.ACTIVITY_TYPE_OTHER
);

ℹ️ See also:

Optional allowIdenticalLocations

allowIdenticalLocations: boolean

[Android only] Allow recording locations which are duplicates of the previous.

break

By default, the Android plugin will ignore a received location when it is identical to the previous location. Set true to override this behaviour and record every location, regardless if it is identical to the last location.

In the logs, you will see a location being ignored:

TSLocationManager:   ℹ️  IGNORED: same as last location

An identical location is often generated when changing state from stationary -> moving, where a single location is first requested (the BackgroundGeolocation.onMotionChange location) before turning on regular location updates. Changing geolocation config params can also generate a duplicate location (eg: changing distanceFilter).

Optional autoSync

autoSync: boolean

Immediately upload each recorded location to your configured url.

break

Default is true. If you've enabeld HTTP feature by configuring an url, the plugin will attempt to HTTP POST each location to your server as soon as it is recorded. If you set autoSync false, it's up to you to manually execute the BackgroundGeolocation.sync method to initate the HTTP POST — the SDK will continue to persist every recorded location in the SQLite database until you execute BackgroundGeolocation.sync.

example
BackgroundGeolocation.ready({
  url: 'http://my.server.com/locations',
  autoSync: true,
  params: {
    user_id: 1234
  }
})

ℹ️ See also:

Optional autoSyncThreshold

autoSyncThreshold: number

The minimum number of persisted records the plugin must accumulate before triggering an autoSync action.

break

Defaults to 0 (no threshold). If you configure a value greater-than 0, the plugin will wait until that many locations are recorded before executing HTTP requests to your server through your configured url.

ℹ️ Configuring autoSyncThreshold in conjunction with batchSync true can conserve battery by reducing the number of HTTP requets, since HTTP requets consume far more energy / second than GPS.

example
BackgroundGeolocation.ready({
  url: 'http://my.server.com/locations',
  autoSync: true,
  autoSyncThreshold: 5,
  batchSync: true
})
             1  2  3  4  5    1  2  3  4  5
Locations: __|__|__|__|__|____|__|__|__|__|___...

                        POST             POST
  Network: ______________|________________|___...

Optional batchSync

batchSync: boolean

POST multiple locations to your url in a single HTTP request.

Default is false. If you've enabled HTTP feature by configuring an url, batchSync true will POST all the locations currently stored in native SQLite datbase to your server in a single HTTP POST request. With batchSync false, an HTTP POST request will be initiated for each location in database.

batchSync: true — All accumulated locations POSTed in 1 HTTP request.

example
// Using batchSync: true
BackgroundGeolocation.ready({
  url: 'http://my.server.com/locations',
  autoSync: true,
  autoSyncThreshold: 5,
  batchSync: true
})
             1  2  3  4  5    1  2  3  4  5
Locations: __|__|__|__|__|____|__|__|__|__|___...

                        POST            POST
  Network: ______________|________________|___...

batchSync: false — 1 POST per location

example
// With batchSync: false
BackgroundGeolocation.ready({
  url: 'http://my.server.com/locations',
  autoSync: true,
  autoSyncThreshold: 5,
  batchSync: false
})
             1  2  3  4  5    1  2  3  4  5
Locations: __|__|__|__|__|____|__|__|__|__|___...

                         POST             POST
  Network: ______________|||||____________|||||___...

ℹ️ See also:

Optional debug

debug: boolean

Configure the plugin to emit sound effects and local-notifications during development.

break

Defaults to false. When set to true, the plugin will emit debugging sounds and notifications for life-cycle events of BackgroundGeolocation.

iOS

In you wish to hear debug sounds in the background, you must manually enable the background-mode:

[x] Audio and Airplay background mode in Background Capabilities of XCode.

\

ℹ️ See also:

Optional deferTime

deferTime: number

[Android only] Sets the maximum wait time in milliseconds for location updates.

Defaults to 0 (no defer). If you pass a value at least 2x larger than the interval specified with locationUpdateInterval, then location delivery may be delayed and multiple locations can be delivered at once. Locations are determined at the locationUpdateInterval rate, but can be delivered in batch after the interval you set in this method. This can consume less battery and give more accurate locations, depending on the device's hardware capabilities. You should set this value to be as large as possible for your needs if you don't need immediate location delivery.

Optional desiredAccuracy

desiredAccuracy: LocationAccuracy

Specify the desired-accuracy of the geolocation system.

The following constants are defined upon the BackgroundGeolocation class:

Name Location Providers Description
BackgroundGeolocation.DESIRED_ACCURACY_NAVIGATION (iOS only) GPS + Wifi + Cellular Highest power; highest accuracy
BackgroundGeolocation.DESIRED_ACCURACY_HIGH GPS + Wifi + Cellular Highest power; highest accuracy
BackgroundGeolocation.DESIRED_ACCURACY_MEDIUM Wifi + Cellular Medium power; Medium accuracy;
BackgroundGeolocation.DESIRED_ACCURACY_LOW Wifi (low power) + Cellular Lower power; No GPS
BackgroundGeolocation.DESIRED_ACCURACY_VERY_LOW Cellular only Lowest power; lowest accuracy
BackgroundGeolocation.DESIRED_ACCURACY_LOWEST (iOS only) Lowest power; lowest accuracy

⚠️ Note:

  • Only DESIRED_ACCURACY_HIGH uses GPS. speed, heading and altitude are available only from GPS.
example
BackgroundGeoloction.ready({
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH
});

For platform-specific information about location accuracy, see the corresponding API docs:

Optional desiredOdometerAccuracy

desiredOdometerAccuracy: number

The maximum location accuracy allowed for a location to be used for Location.odometer calculations.

Defaults to 100. If a location arrives having accuracy > desiredOdometerAccuracy, that location will not be used to update the odometer. If you only want to calculate odometer from GPS locations, you could set desiredOdometerAccuracy: 10. This will prevent odometer updates when a device is moving around indoors, in a shopping mall, for example.

Optional disableElasticity

disableElasticity: boolean

Defaults to false. Set true to disable automatic, speed-based distanceFilter auto-scaling. By default, the SDK automatically increases distanceFilter as speed increases (and decreases it as speed decreases) in order to record fewer locations and conserve energy.

break

Note the following real example of "elasticity" on highway 101 towards San Francisco as the driver slows down while running into slower traffic — locations become compressed as distanceFilter decreases.

distanceFilter at highway speed

ℹ️ See also:

Optional disableLocationAuthorizationAlert

disableLocationAuthorizationAlert: boolean

Disables automatic authorization alert when plugin detects the user has disabled location authorization.

break

You will be responsible for handling disabled location authorization by listening to the BackgroundGeolocation.onProviderChange event.

By default, the plugin automatically shows a native alert (configured via locationAuthorizationAlert and locationAuthorizationRequest to the user when location-services are disabled, directing them to the settings screen. If you do not desire this automated behaviour, set disableLocationAuthorizationAlert: true.

example
BackgroundGeolocation.onProviderChange((event) => {
  console.log('[onProviderChange] ', event);

  if (!provider.enabled) {
    alert('Please enable location services');
  }
});

BackgroundGeolocation.ready({
  disableLocationAuthorizationAlert: true
});

Optional disableMotionActivityUpdates

disableMotionActivityUpdates: boolean

[iOS only] Disable the plugin requesting "Motion & Fitness" authorization from the User.

break

Defaults to false. Set true to disable iOS CMMotionActivityManager-based motion-activity updates (eg: walking, in_vehicle). This feature requires a device having the M7 co-processor (ie: iPhone 5s and up).

⚠️ Warning:

  • The plugin is HIGHLY optimized for motion-activity-updates. If you do disable this, the plugin will drain more battery power. You are STRONGLY advised against disabling this. You should explain to your users with an appropriate NSMotionUsageDescription in your Info.plist file, for example:

    "Motion activity detection increases battery efficiency by intelligently toggling location-tracking" off when your device is detected to be stationry.

ℹ️ Note:

  • This feature will ask the user for "Health updates" permission using the NSMotionUsageDescription in your Info.plist. If you do not wish to ask the user for the "Health updates", set this option to true; However, you will no longer receive accurate activity data in the recorded locations.

Optional disableStopDetection

disableStopDetection: boolean

Disable motion-activity related stop-detection.

break

iOS

Disables the accelerometer-based Stop-detection System. When disabled, the plugin will use the default iOS behaviour of automatically turning off location-services when the device has stopped for exactly 15 minutes. When disabled, you will no longer have control over stopTimeout.

To completely disable automatically turning off iOS location-services, you must also provide pausesLocationUpdatesAutomatically false.

example
BackgroundGeolocation.ready({
  disableStopDetection: true,
  pausesLocationUpdatesAutomatically: false
});

⚠️ iOS location-services will never turn off!

With the above configuration, iOS location-services will never turn off and you could quickly discharge the battery. Do not do this unless you know exactly what you're doing (eg: A jogging app with [Start workout] / [Stop Workout] buttons executing BackgroundGeolocation.changePace).

iOS Stop-detection timing

Android

Location-services will never turn OFF if you set this to true! It will be purely up to you or the user to execute BackgroundGeolocation.changePace false or BackgroundGeolocation.stop to turn off location-services.

Optional distanceFilter

distanceFilter: number

The minimum distance (measured in meters) a device must move horizontally before an update event is generated.

However, by default, distanceFilter is elastically auto-calculated by the plugin: When speed increases, distanceFilter increases; when speed decreases, so too does distanceFilter.

break

ℹ️ Note:

distanceFilter is auto-scaled by rounding speed to the nearest 5 m/s and adding distanceFilter meters for each 5 m/s increment.

For example, at biking speed of 7.7 m/s with a configured distanceFilter: 30:

example
  rounded_speed = round(7.7, 5)
  => 10
  multiplier = rounded_speed / 5
  => 10 / 5 = 2
  adjusted_distance_filter = multiplier * distanceFilter
  => 2 * 30 = 60 meters

At highway speed of 27 m/s with a configured distanceFilter: 50:

example
  rounded_speed = round(27, 5)
  => 30
  multiplier = rounded_speed / 5
  => 30 / 5 = 6
  adjusted_distance_filter = multiplier * distanceFilter * elasticityMultipiler
  => 6 * 50 = 300 meters

Note the following real example of "elasticity" on highway 101 towards San Francisco as the driver slows down while running into slower traffic — locations become compressed as distanceFilter decreases.

distanceFilter at highway speed

Compare now background-geolocation in the scope of a city. In this image, the left-hand track is from a cab-ride, while the right-hand track is walking speed.

distanceFilter at city scale

Optional elasticityMultiplier

elasticityMultiplier: number

Controls the scale of automatic speed-based distanceFilter elasticity.

Increasing elasticityMultiplier will result in fewer location samples as speed increases. A value of 0 has the same effect as disableElasticity true.

Optional enableHeadless

enableHeadless: boolean

[Android only] Enables "Headless" operation allowing you to respond to events after you app has been terminated with stopOnTerminate false.

break

Defaults to false. In this Android terminated state, where only the plugin's foreground-service remains running, you can respond to all the plugin's events with your own callback.

ℹ️ Note:

  • Requires stopOnTerminate false.
  • If you've configured stopOnTerminate false, BackgroundGeolocation will continue to record locations (and post them to your configured url) regardless of enabledHeadless: true. You should enable this option only if you wish to perform some custom work during the headless state (for example, posting a local notification).
  • For more information, see the Wiki Android Headless Mode.

Optional enableTimestampMeta

enableTimestampMeta: boolean

[Android-only] Enable extra timestamp meta data to be appended to each recorded location, including system-time.

break

Some developers have reported GPS Location.timestamp issues with some Android devices. This option will append extra meta-data related to the device's system time.

Java implementation

if (enableTimestampMeta) {
    JSONObject timestampMeta = new JSONObject();
    timestampMeta.put("time", mLocation.getTime());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        timestampMeta.put("systemClockElaspsedRealtime", SystemClock.elapsedRealtimeNanos()/1000000);
        timestampMeta.put("elapsedRealtime", mLocation.getElapsedRealtimeNanos()/1000000);
    } else {
        timestampMeta.put("systemTime", System.currentTimeMillis());
    }
    data.put("timestampMeta", timestampMeta);
}

Optional extras

extras: Object

Optional arbitrary key/values {} applied to each recorded location.

πŸ“˜ See HTTP Guide: HttpEvent

example
BackgroundGeolocation.ready({
  url: 'https://my-server.com/locations',
  extras: {
    'route_id': 1234
  },
  params: {
    'device_id': 'abc123'
  }
});

Observing incoming requests at your server:

example
- POST /locations
{
  "device_id": "abc123" // <-- params appended to root of JSON
  "location": {
    "coords": {
      "latitude": 45.51927004945047,
      "longitude": -73.61650072045029,
      .
      .
      .
    },
    "extras": {  // <-- extras appended to *each* location
      "route_id": 1234
    }
  }
}

Optional fastestLocationUpdateInterval

fastestLocationUpdateInterval: number

[Android only] Explicitly set the fastest interval for location updates, in milliseconds.

break

This controls the fastest rate at which your application will receive location updates, which might be faster than locationUpdateInterval in some situations (for example, if other applications are triggering location updates).

This allows your application to passively acquire locations at a rate faster than it actively acquires locations, saving power.

Unlike locationUpdateInterval, this parameter is exact. Your application will never receive updates faster than this value.

If you don't call this method, a fastest interval will be set to 30000 (30s).

An interval of 0 is allowed, but not recommended, since location updates may be extremely fast on future implementations.

If fastestLocationUpdateInterval is set slower than locationUpdateInterval, then your effective fastest interval is locationUpdateInterval.

ℹ️ See also:

Optional forceReloadOnBoot

forceReloadOnBoot: boolean

Force launch your terminated App after a device reboot or application update.

break

When the user reboots their device with BackgroundGeolocation configured with startOnBoot true, only the plugin's pure native background-service begins running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional forceReloadOnGeofence

forceReloadOnGeofence: boolean

Force launch your terminated App after a BackgroundGeolocation.onGeofence event.

break

When the user terminates your Android app with BackgroundGeolocation configured with stopOnTerminate false, the foreground MainActivity (where your Flutter app lives) will terminate — only the plugin's pure native background-service is running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional forceReloadOnHeartbeat

forceReloadOnHeartbeat: boolean

Force launch your terminated App after a BackgroundGeolocation.onHeartbeat event.

break

When the user terminates your Android app with BackgroundGeolocation configured with stopOnTerminate false, the foreground MainActivity (where your application code lives) will terminate — only the plugin's pure native background-service is running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional forceReloadOnLocationChange

forceReloadOnLocationChange: boolean

Force launch your terminated App after a BackgroundGeolocation.onLocation event.

break

When the user terminates your Android app with BackgroundGeolocation configured with stopOnTerminate false, the foreground MainActivity (where your Flutter app lives) will terminate — only the plugin's pure native background-service is running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional forceReloadOnMotionChange

forceReloadOnMotionChange: boolean

Force launch your terminated App after a BackgroundGeolocation.onMotionChange event.

break

When the user terminates your Android app with BackgroundGeolocation configured with stopOnTerminate false, the foreground MainActivity (where your Flutter app lives) will terminate — only the plugin's pure native background-service is running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional forceReloadOnSchedule

forceReloadOnSchedule: boolean

Force launch your terminated App after a BackgroundGeolocation.onSchedule event.

break

When the user terminates your Android app with BackgroundGeolocation configured with stopOnTerminate false, the foreground MainActivity (where your Flutter app lives) will terminate — only the plugin's pure native background-service is running, "headless", in this case. The background service will continue tracking the location. However, the background service can optionally re-launch your foreground application.

⚠️ Warning:

  • When the background service re-launches your application, it will briefly appear in the foreground before immediately minimizing. If the user has their phone on at the time, they will see a brief flash of your app appearing and minimizing.

Optional foregroundService

foregroundService: boolean

[Android only] Configure the plugin service to run as a more robust "Foreground Service".

break

⚠️ Android 8.0+

Defaults to true and cannot be set to false. Due to strict new Background Execution Limits in Android 8, the plugin enforces foregroundService: true.

A persistent notification is required by the operating-system with a foreground-service. It cannot be hidden.

Android < 8.0

Defaults to false. When the Android OS is under memory pressure from other applications (eg: a phone call), the OS can and will free up memory by terminating other processes and scheduling them for re-launch when memory becomes available. If you find your tracking being terminated unexpectedly, this is why.

If you set this option to true, the plugin will run its Android service in the foreground, supplying the ongoing notification to be shown to the user while in this state. Running as a foreground-service makes the tracking-service much more inmmune to OS killing it due to memory/battery pressure. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser).

ℹ️ See also:

Optional geofenceInitialTriggerEntry

geofenceInitialTriggerEntry: boolean

When a device is already within a just-created geofence, fire the enter transition immediately.

Defaults to true. Set false to disable triggering a geofence immediately if device is already inside it.

break

ℹ️ See also:

Optional geofenceProximityRadius

geofenceProximityRadius: number

The radius around current location to query for geofences to activate monitoring upon.

The default and minimum is 1000 meters. See related event BackgroundGeolocation.onGeofencesChange. When using Geofences, the plugin activates only thoses in proximity (the maximim geofences allowed to be simultaneously monitored is limited by the platform, where iOS allows only 20 and Android. However, the plugin allows you to create as many geofences as you wish (thousands even). It stores these in its database and uses spatial queries to determine which 20 or 100 geofences to activate.

break

ℹ️ See also:

Optional geofenceTemplate

geofenceTemplate: string

Optional custom template for rendering GeofenceEvent JSON request data in HTTP requests.

break

The geofenceTemplate is similar to locationTemplate with the addition of two extra geofence.* tags.

The geofenceTemplate will be evaulated for variables using Ruby erb-style tags:

<%= variable_name %>

ℹ️ See also:

example
BackgroundGeolocation.ready({
  geofenceTemplate: '{ "lat":<%= latitude %>, "lng":<%= longitude %>, "geofence":"<%= geofence.identifier %>:<%= geofence.action %>" }'
});

// Or use a compact [Array] template!
BackgroundGeolocation.{(
  geofenceTemplate: '[<%= latitude %>, <%= longitude %>, "<%= geofence.identifier %>", "<%= geofence.action %>"]'
)

⚠️ quoting String data.

The plugin does not automatically apply double-quotes around String data. The plugin will attempt to JSON encode your template exactly as you're configured.

The following will generate an error:

example
BackgroundGeolocation.ready({
  locationTemplate: '{"timestamp": <%= timestamp %>}'
});

Since the template-tag timestamp renders a string, the rendered String will look like this, generating a JSON error:

example
{"timestamp": 2018-01-01T12:01:01.123Z}

The correct geofenceTemplate is:

example
BackgroundGeolocation.ready({
  geofenceTemplate: '{"timestamp": "<%= timestamp %>"}'
});
example
{"timestamp": "2018-01-01T12:01:01.123Z"}

Template Tags

The tag-list is identical to locationTemplate with the addition of geofence.identifier and geofence.action.

Tag Type Description
geofence.identifier String Which geofence?
geofence.action String ENTER/EXIT
latitude Float
longitude Float
speed Float Meters
heading Float Degress
accuracy Float Meters
altitude Float Meters
altitude_accuracy Float Meters
timestamp String ISO-8601
uuid String Unique ID
event String motionchange,geofence,heartbeat,providerchange
odometer Float Meters
activity.type String still,on_foot,running,on_bicycle,in_vehicle,unknown
activity.confidence Integer 0-100%
battery.level Float 0-100%
battery.is_charging Boolean Is device plugged in?

Optional headers

headers: Object

Optional HTTP headers applied to each HTTP request.

example
BackgroundGeolocation.ready({
  url: 'https://my.server.com',
  headers: {
    'authorization': "Bearer <a secret key>",
    'X-FOO": "BAR'
  }
});

Observing incoming requests at your server:

POST /locations
{
  "host": "tracker.transistorsoft.com",
  "content-type": "application/json",
  "content-length": "456"
  .
  .
  .
  "authorization": "Bearer <a secret key>",
  "X-FOO": "BAR"
}

ℹ️ Note:

  • The plugin automatically applies a number of required headers, including "content-type": "application/json"

Optional heartbeatInterval

heartbeatInterval: number

Controls the rate (in seconds) the BackgroundGeolocation.onHeartbeat event will fire.

break

⚠️ Warning:

example
BackgroundGeolocation.ready({
  heartbeatInterval: 60
});

BackgroundGeolocation.onHeartbeat((event) => {
  console.log('[onHeartbeat] ', event);

  // You could request a new location if you wish.
  BackgroundGeolocation.getCurrentPosition({
    samples: 1,
    persist: true
  }).then((location) => {
    console.log('[getCurrentPosition] ', location);
  });
});

ℹ️ See also:

Optional httpRootProperty

httpRootProperty: string

The root property of the JSON schema where location-data will be attached.

example
BackgroundGeolocation.ready({
  httpRootProperty: "myData",
  url: "https://my.server.com"
});
{
    "myData":{
        "coords": {
            "latitude":23.232323,
            "longitude":37.373737
        }
    }
}

You may also specify the character httpRootProperty:"." to place your data in the root of the JSON:

example
{
    "coords": {
        "latitude":23.232323,
        "longitude":37.373737
    }
}

ℹ️ See also:

Optional httpTimeout

httpTimeout: number

HTTP request timeout in milliseconds.

HTTP request timeouts will fire the BackgroundGeolocation.onHttp. Defaults to 60000 ms.

example
BackgroundGeolocation.onHttp((response) => {
  let success = response.success;
  if (!success) {
    console.log('[onHttp] FAILURE: ', response);
  }
});

BackgroundGeolocation.ready({
  url: 'https://my-server.com/locations',
  httpTimeout: 3000
);

ℹ️ See also:

Optional isMoving

isMoving: boolean

Configure the initial tracking-state after BackgroundGeolocation.start is called.

The plugin will immediately enter the tracking-state, by-passing the stationary state. If the device is not currently moving, the stop-detection system will still engage. After stopTimeout minutes without movement, the plugin will enter the stationary state, as usual.

example
let state = await BackgroundGeolocation.ready({
  isMoving: true
});

if (!state.enabled) {
  BackgroundGeolocation.start();
}
// Location-services are now on and the plugin is recording a location
// each <a href="_react_native_background_geolocation_.config.html#distancefilter">distanceFilter</a> meters.

Optional locationAuthorizationAlert

locationAuthorizationAlert: LocationAuthorizationAlert

[iOS only] Controls the text-elements of the plugin's location-authorization dialog.

break

When you configure the plugin locationAuthorizationRequest Always or WhenInUse and the user changes the mode in the app's location-services settings or disabled location-services, the plugin will display an Alert dialog directing the user to the Settings screen. locationAuthorizationAlert allows you to configure all the Strings for that Alert popup and accepts an {} containing the following keys:

example
BackgroundGeolocation.ready({
  locationAuthorizationAlert: {
    titleWhenNotEnabled: 'Yo, location-services not enabled',
    titleWhenOff: 'Yo, location-services OFF',
    instructions: 'You must enable "Always" in location-services, buddy',
    cancelButton: 'Cancel',
    settingsButton: 'Settings'
  }
})

⚠️ Warning:

  • If you choose to configure locationAuthorizationAlert, you must provide ALL the keys of LocationAuthorizationAlert keys — not just some.

Optional locationAuthorizationRequest

locationAuthorizationRequest: LocationAuthorizationRequest

[iOS only] Defines the desired iOS location-authorization request you wish for the user to authorize.

break

locationAuthorizationRequest tells the plugin the mode it expects to have been authorized with by the user. If the user changes this mode in their settings, the plugin will detect this (See locationAuthorizationAlert). Defaults to Always. WhenInUse will display a blue bar at top-of-screen informing user that location-services are on.

If you configure Any, the plugin allow the user to choose either Always or WhenInUse. The plugin will not show the locationAuthorizationAlert dialog when the user changes the selection in Privacy->Location Services.

⚠️ Warning:

  • Configuring WhenInUse will disable many of the plugin's features, since iOS forbids any API which operates in the background to operate (such as geofences, which the plugin relies upon to automatically engage background tracking).

Optional locationTemplate

locationTemplate: string

Optional custom template for rendering Location JSON request data in HTTP requests.

break

The locationTemplate will be evaulated for variables using Ruby erb-style tags:

<%= variable_name %>
example
BackgroundGeolocation.ready({
  locationTemplate: '{"lat":<%= latitude %>,"lng":<%= longitude %>,"event":"<%= event %>",isMoving:<%= isMoving %>}'
});

// Or use a compact [Array] template!
BackgroundGeolocation.ready({
  locationTemplate: '[<%=latitude%>, <%=longitude%>, "<%=event%>", <%=is_moving%>]'
))

⚠️ quoting String data.

The plugin does not automatically apply double-quotes around String data. The plugin will attempt to JSON encode your template exactly as you're configured.

The following will generate an error:

example
BackgroundGeolocation.ready({
  locationTemplate: '{"timestamp": <%= timestamp %>}'
});

Since the template-tag timestamp renders a string, the rendered String will look like this, generating a JSON error:

example
{"timestamp": 2018-01-01T12:01:01.123Z}

The correct locationTemplate is:

example
BackgroundGeolocation.ready({
  locationTemplate: '{"timestamp": "<%= timestamp %>"}'
});
example
{"timestamp": "2018-01-01T12:01:01.123Z"}

Configured extras:

If you've configured extras, these key-value pairs will be merged directly onto your location data. For example:

example
BackgroundGeolocation.ready({
  httpRootProperty: 'data',
  locationTemplate: '{"lat":<%= latitude %>,"lng":<%= longitude %>}',
  extras: {
    "foo": "bar"
  }
)

Will result in JSON:

example
{
    "data": {
        "lat":23.23232323,
        "lng":37.37373737,
        "foo":"bar"
    }
}

Template Tags

Tag Type Description
latitude Float
longitude Float
speed Float Meters
heading Float Degress
accuracy Float Meters
altitude Float Meters
altitude_accuracy Float Meters
timestamp String ISO-8601
uuid String Unique ID
event String motionchange,geofence,heartbeat,providerchange
odometer Float Meters
activity.type String still,on_foot,running,on_bicycle,in_vehicle,unknown
activity.confidence Integer 0-100%
battery.level Float 0-100%
battery.is_charging Boolean Is device plugged in?

ℹ️ See also:

Optional locationTimeout

locationTimeout: number

Disable automatic, speed-based distanceFilter scaling.

Defaults to false. Set true to disable automatic, speed-based distanceFilter elasticity.

Optional locationUpdateInterval

locationUpdateInterval: number

[Android only] Set the desired interval for active location updates, in milliseconds.

break

⚠️ Note:

Set the desired interval for active location updates, in milliseconds.

The location client will actively try to obtain location updates for your application at this interval, so it has a direct influence on the amount of power used by your application. Choose your interval wisely.

This interval is inexact. You may not receive updates at all (if no location sources are available), or you may receive them slower than requested. You may also receive them faster than requested (if other applications are requesting location at a faster interval).

Applications with only the coarse location permission may have their interval silently throttled.\

example
BackgroundGeolocation.ready({
  distanceFilter: 0,            // Must be 0 or locationUpdateInterval is ignored!
  locationUpdateInterval: 5000  // Get a location every 5 seconds
});

ℹ️ See also:

Optional locationsOrderDirection

locationsOrderDirection: string

Controls the order that locations are selected from the database (and uploaded to your server).

Defaults to ascending (ASC), where oldest locations are synced first. Descending (DESC) uploads latest locations first.

ℹ️ See also:

Optional logLevel

logLevel: LogLevel

Controls the volume of recorded events in the plugin's logging database.

BackgroundGeolocation contains powerful logging features. By default, the plugin boots with a value of BackgroundGeolocation.LOG_LEVEL_OFF, storing logMaxDays (default 3) days worth of logs in its SQLite database.

The following log-levels are defined as constants on this BackgroundGeolocation class:

Label
BackgroundGeolocation.LOG_LEVEL_OFF
BackgroundGeolocation.LOG_LEVEL_ERROR
BackgroundGeolocation.LOG_LEVEL_WARNING
BackgroundGeolocation.LOG_LEVEL_INFO
BackgroundGeolocation.LOG_LEVEL_DEBUG
BackgroundGeolocation.LOG_LEVEL_VERBOSE
break

Example log data:

09-19 11:12:18.716 ╔═════════════════════════════════════════════
09-19 11:12:18.716 β•‘ BackgroundGeolocation Service started
09-19 11:12:18.716 ╠═════════════════════════════════════════════
09-19 11:12:18.723 [c.t.l.BackgroundGeolocationService d]
09-19 11:12:18.723   βœ…  Started in foreground
09-19 11:12:18.737 [c.t.l.ActivityRecognitionService a]
09-19 11:12:18.737   🎾  Start activity updates: 10000
09-19 11:12:18.761 [c.t.l.BackgroundGeolocationService k]
09-19 11:12:18.761   πŸ”΄  Stop heartbeat
09-19 11:12:18.768 [c.t.l.BackgroundGeolocationService a]
09-19 11:12:18.768   🎾  Start heartbeat (60)
09-19 11:12:18.778 [c.t.l.BackgroundGeolocationService a]
09-19 11:12:18.778   πŸ”΅  setPace: null β†’ false
09-19 11:12:18.781 [c.t.l.adapter.TSConfig c] ℹ️   Persist config
09-19 11:12:18.794 [c.t.locationmanager.util.b a]
09-19 11:12:18.794   ℹ️  LocationAuthorization: Permission granted
09-19 11:12:18.842 [c.t.l.http.HttpService flush]
09-19 11:12:18.842 ╔═════════════════════════════════════════════
09-19 11:12:18.842 β•‘ HTTP Service
09-19 11:12:18.842 ╠═════════════════════════════════════════════
09-19 11:12:19.000 [c.t.l.BackgroundGeolocationService onActivityRecognitionResult] still (100%)
09-19 11:12:21.314 [c.t.l.l.SingleLocationRequest$2 onLocationResult]
09-19 11:12:21.314 ╔═════════════════════════════════════════════
09-19 11:12:21.314 β•‘ SingleLocationRequest: 1
09-19 11:12:21.314 ╠═════════════════════════════════════════════
09-19 11:12:21.314 β•Ÿβ”€ πŸ“  Location[fused 45.519239,-73.617058 hAcc=15]999923706055 vAcc=2 sAcc=??? bAcc=???
09-19 11:12:21.327 [c.t.l.l.TSLocationManager onSingleLocationResult]
09-19 11:12:21.327   πŸ”΅  Acquired motionchange position, isMoving: false
09-19 11:12:21.342 [c.t.l.l.TSLocationManager a] 15.243
09-19 11:12:21.405 [c.t.locationmanager.data.a.c persist]
09-19 11:12:21.405   βœ…  INSERT: bca5acc8-e358-4d8f-827f-b8c0d556b7bb
09-19 11:12:21.423 [c.t.l.http.HttpService flush]
09-19 11:12:21.423 ╔═════════════════════════════════════════════
09-19 11:12:21.423 β•‘ HTTP Service
09-19 11:12:21.423 ╠═════════════════════════════════════════════
09-19 11:12:21.446 [c.t.locationmanager.data.a.c first]
09-19 11:12:21.446   βœ…  Locked 1 records
09-19 11:12:21.454 [c.t.l.http.HttpService a]
09-19 11:12:21.454   πŸ”΅  HTTP POST: bca5acc8-e358-4d8f-827f-b8c0d556b7bb
09-19 11:12:22.083 [c.t.l.http.HttpService$a onResponse]
09-19 11:12:22.083   πŸ”΅  Response: 200
09-19 11:12:22.100 [c.t.locationmanager.data.a.c destroy]
09-19 11:12:22.100   βœ…  DESTROY: bca5acc8-e358-4d8f-827f-b8c0d556b7bb
09-19 11:12:55.226 [c.t.l.BackgroundGeolocationService onActivityRecognitionResult] still (100%)
example
BackgroundGeolocation.ready({
  logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE
});

ℹ️ See also:

⚠️ Warning:

Optional logMaxDays

logMaxDays: number

Maximum number of days to persist a log-entry in database.

break

Defaults to 3 days.

See also:

Optional maxBatchSize

maxBatchSize: number

Controls the number of records attached to each batch HTTP request.

break

Defaults to -1 (no maximum). If you've enabled HTTP feature by configuring an url with batchSync true, this parameter will limit the number of records attached to each batch request. If the current number of records exceeds the maxBatchSize, multiple HTTP requests will be generated until the location queue is empty.

The plugin can potentially accumulate mega-bytes worth of location-data if operating in a disconnected environment for long periods. You will not want to batchSync true a large amount of data in a single HTTP request.

ℹ️ See also:

Optional maxDaysToPersist

maxDaysToPersist: number

Maximum number of days to store a geolocation in plugin's SQLite database.

break

When your server fails to respond with HTTP 200 OK, the plugin will continue periodically attempting to upload to your server server until maxDaysToPersist when it will give up and remove the location from the database.

Optional maxRecordsToPersist

maxRecordsToPersist: number

Maximum number of records to persist in plugin's SQLite database.

Default -1 means no limit.

ℹ️ See also:

Optional method

method: HttpMethod

The HTTP method to use when creating an HTTP request to your configured url.

Defaults to POST. Valid values are POST, PUT and OPTIONS.

example
BackgroundGeolocation.ready({
  url: 'http://my-server.com/locations',
  method: 'PUT'
});

ℹ️ See also:

Optional minimumActivityRecognitionConfidence

minimumActivityRecognitionConfidence: number

The minimum motion-activity confidence to conclude a device is moving.

break

Defaults to 75%. Each activity-recognition-result returned by the API is tagged with a "confidence" level expressed as a %. You can set your desired confidence to trigger a BackgroundGeolocation.onMotionChange event.

This setting can be helpful for poor quality Android devices missing crucial motion sensors (accelerometer, gyroscope, magnetometer) by adjusting the confidence lower. You can determine missing sensors on a device using the method getSensors.

example
BackgroundGeolocation.ready({
  minimumActivityRecognitionConfidence: 50 // <-- trigger less confidently.
});

Optional notificationChannelName

notificationChannelName: string

Configure the name of the plugin's notification-channel used to display the foregroundService notification.

break

On Android O+, the plugin's foreground-service needs to create a "Notification Channel". The name of this channel can be seen in:

Settings->App & Notifications->Your App.

Defaults to your application's name from AndroidManifest.

\

example
BackgroundGeolocation.ready({
  notificationChannelName: "Location Tracker"
});

// or with #setConfig
BackgroundGeolocation.setConfig({
  notificationChannelName: "My new channel name"
});

Optional notificationColor

notificationColor: string

Configure the color of the persistent notification icon in the Notification Bar when running with foregroundService true

break

Defaults to null. When running the service with foregroundService: true, Android requires a persistent notification. This will configure the color of the notification icon (API >= 21).

Supported formats are:

  • #RRGGBB
  • #AARRGGBB

Optional notificationLargeIcon

notificationLargeIcon: string

Configure the large icon of the persistent notification in the Notification Bar when running with foregroundService true

break

When running the service with foregroundService: true, Android requires a persistent notification in the Notification Bar. This allows you customize that icon. Defaults to your application icon.

⚠️ Warning:

  • You must specify the type (drawable|mipmap) of resource you wish to use in the following format: {type}/icon_name
  • Do not append the file-extension (eg: .png)
example
// 1. drawable
BackgroundGeolocation.ready({
  notificationSmallIcon: "drawable/my_custom_notification_small_icon"
});

// 2. mipmap
BackgroundGeolocation.ready({
  notificationSmallIcon: "mipmap/my_custom_notification_small_icon"
});

ℹ️ See also:

Optional notificationPriority

notificationPriority: NotificationPriority

When running the service with foregroundService: true, Android requires a persistent notification in the Notification Bar. This will control the priority of that notification as well as the position of the notificaiton-bar icon.

The following notificationPriority values defined as static constants upon the BackgroundGeolocation object:

Value Description
BackgroundGeolocation.NOTIFICATION_PRIORITY_DEFAULT Notification weighted to top of list; notification-bar icon weighted left
BackgroundGeolocation.NOTIFICATION_PRIORITY_HIGH Notification strongly weighted to top of list; notification-bar icon strongly weighted to left
BackgroundGeolocation.NOTIFICATION_PRIORITY_LOW Notification weighted to bottom of list; notification-bar icon weighted right
BackgroundGeolocation.NOTIFICATION_PRIORITY_MAX Same as NOTIFICATION_PRIORITY_HIGH
BackgroundGeolocation.NOTIFICATION_PRIORITY_MIN Notification strongly weighted to bottom of list; notification-bar icon hidden
example
BackgroundGeolocation.ready({
  foregroundService: true,
  notificationPriority: BackgroundGeolocation.NOTIFICATION_PRIORITY_MIN
});

Optional notificationSmallIcon

notificationSmallIcon: string

Configure the small icon of the persistent notification in the Notification Bar when running with foregroundService true

break

When running the service with foregroundService: true, Android requires a persistent notification in the Notification Bar. This allows you customize that icon. Defaults to your application icon.

⚠️ Warning:

  • You must specify the type (drawable|mipmap) of resource you wish to use in the following format: {type}/icon_name
  • Do not append the file-extension (eg: .png)
example
// 1. drawable
BackgroundGeolocation.ready({
  notificationSmallIcon: "drawable/my_custom_notification_small_icon"
});

// 2. mipmap
BackgroundGeolocation.ready({
  notificationSmallIcon: "mipmap/my_custom_notification_small_icon"
});

ℹ️ See also:

Optional notificationText

notificationText: string

Configure the text of the persistent notification in the Notification Bar when running with foregroundService true

break

Defaults to "Location service activated". When running the service with foregroundService: true, Android requires a persistent notification. This will configure the text of that notification.

Optional notificationTitle

notificationTitle: string

Configure the title of the persistent notification in the Notification Bar when running with foregroundService true

break

Defaults to the application name from AndroidManifest. When running the service with foregroundService: true, Android requires a persistent notification. This will configure the title of that notification.

Optional params

params: Object

Optional HTTP params appended to the JSON body of each HTTP request.

example
BackgroundGeolocation.ready({
  url: 'https://my-server.com/locations',
  params: {
    'user_id': 1234,
    'device_id': 'abc123'
  }
);

Observing the HTTP request arriving at your server:

example
POST /locations
 {
  "location": {
    "coords": {
      "latitude": 45.51927004945047,
      "longitude": -73.61650072045029
      .
      .
      .
    }
  },
  "user_id": 1234,  // <-- params appended to the data.
  "device_id": 'abc123'
}

ℹ️ See also:

Optional pausesLocationUpdatesAutomatically

pausesLocationUpdatesAutomatically: boolean

[iOS only] Configure iOS location API to never automatically turn off.

break

⚠️ Warning:

  • This option should generally be left undefined. You should only specifiy this option if you know exactly what you're doing.

The default behaviour of the plugin is to turn off location-services automatically when the device is detected to be stationary for stopTimeout minutes. When set to false, location-services will never be turned off (and disableStopDetection will automatically be set to true) — it's your responsibility to turn them off when you no longer need to track the device. This feature should not generally be used. preventSuspend will no longer work either.

Optional preventSuspend

preventSuspend: boolean

[iOS only] Prevent iOS from suspending your application in the background after location-services have been switched off.

break

Defaults to false. Set true to prevent iOS from suspending your application after location-services have been switched off while running in the background. Must be used in conjunction with a heartbeatInterval.

⚠️ Warning:

  • preventSuspend: true should only be used in very specific use-cases and should typically not be used as it will have a very noticable impact on battery performance. You should carefully manage preventSuspend, engaging it for controlled periods-of-time. You should not expect to run your app in this mode 24 hours / day, 7 days-a-week.
  • When a device is unplugged form power with the screen off, iOS will still throttle BackgroundGeolocation.onHeartbeat events about 2 minutes after entering the background state. However, if the screen is lit up or even the slightest device-motion is detected, BackgroundGeolocation.onHeartbeat events will immediately resume.
example
BackgroundGeolocation.onHeartbeat((event) => {
  console.log('[onHeartbeat] ', event);
});

BackgroundGeolocation.ready({
  preventSuspend: true,
  heartbeatInterval: 60
});

ℹ️ See also:

Optional reset

reset: boolean

Forces BackgroundGeolocation.ready to apply supplied Config with each application launch.

break

Optionally, you can specify reset: true to BackgroundGeolocation.ready. This will esentially force the supplied Config to be applied with each launch of your application.

example
BackgroundGeolocation.ready({
  reset: true,  // <-- set true to ALWAYS apply supplied config; not just at first launch.
  distanceFilter: 50
}, (state) => {
  conosle.log('Ready with reset: true: ', state.distanceFilter);
});

Optional schedule

schedule: Array<string>

Configures an automated, cron-like schedule for the plugin to start / stop tracking at pre-defined times.

example
  "{DAY(s)} {START_TIME}-{END_TIME}"
  • The START_TIME, END_TIME are in 24h format.
  • The DAY param corresponds to the Locale.US, such that Sunday=1; Saturday=7).
  • You may configure a single day (eg: 1), a comma-separated list-of-days (eg: 2,4,6) or a range (eg: 2-6)
example
BackgroundGeolocation.ready({
  .
  .
  .
  schedule: [
    '1 17:30-21:00',    // Sunday: 5:30pm-9:00pm
    '2-6 9:00-17:00',   // Mon-Fri: 9:00am to 5:00pm
    '2,4,6 20:00-00:00',// Mon, Web, Fri: 8pm to midnight (next day)
    '7 10:00-19:00'     // Sat: 10am-7pm
  ]
}).then((state) => {
  // Start the Scheduler
  BackgroundGeolocation.startSchedule();
});

// Listen to #onSchedule events:
BackgroundGeolocation.onSchedule((state) => {
  let enabled = state.enabled;
  console.log('[onSchedule] - enabled? ', enabled);
});
.
.
.
// Later when you want to stop the Scheduler (eg: user logout)
BackgroundGeolocation.stopSchedule();
// You must explicitly stop tracking if currently enabled
BackgroundGeolocation.stop();

// Or modify the schedule with usual #setConfig method
BackgroundGeolocation.setConfig({
  schedule: [
    '1-7 9:00-10:00',
    '1-7 11:00-12:00',
    '1-7 13:00-14:00',
    '1-7 15:00-16:00',
    '1-7 17:00-18:00',
    '2,4,6 19:00-22:00'
  ]
});

Literal Dates

The schedule can also be configured with a literal start date of the form:

example
  "yyyy-mm-dd HH:mm-HH:mm"
example
BackgroundGeolocation.ready({
  schedule: [
    "2018-01-01 09:00-17:00"
  ]
});

Or two literal dates to specify both a start and stop date:

example
  "yyyy-mm-dd-HH:mm yyyy-mm-dd-HH:mm"
example

schedule: [
    "2018-01-01-09:00 2019-01-01-17:00"  // <-- track for 1 year
  ]

iOS

  • iOS cannot evaluate the Schedule at the exact time you configure — it can only evaluate the schedule periodically, whenever your app comes alive.
  • When the app is running in a scheduled off period, iOS will continue to monitor the low-power, significant location changes API (SLC) in order to ensure periodic schedule evaluation. SLC is required in order guarantee periodic schedule-evaluation when you're configured stopOnTerminate false, since the iOS Background Fetch API is halted if user manually terminates the app. SLC will awaken your app whenever a "significant location change" occurs, typically every 1000 meters. If the schedule is currently in an off period, this location will not be persisted nor will it be sent to the BackgroundGeolocation.onLocation event — only the schedule will be evaluated.
  • When a schedule is provided on iOS, it will be evaluated in the following cases:
    • Application pause / resume events.
    • Whenever a location is recorded (including SLC)
    • Background fetch event

Android

The Android Scheduler uses AlarmManager and typically operates on-the-minute.

ℹ️ See also:

Optional startOnBoot

startOnBoot: boolean

Controls whether to resume location-tracking after device is rebooted.

Defaults to false. Set true to engage background-tracking after the device reboots.

break

iOS

iOS cannot immediately engage tracking after a device reboot. Just like stopOnTerminate false, iOS will not re-boot your app until the device moves beyond the stationary geofence around the last known location. In addition, iOS subscribes to "background-fetch" events, which typically fire about every 15 minutes — these too are capable of rebooting your app after a device reboot.

Android

Android will reboot the plugin's background-service immediately after device reboot. However, just like stopOnTerminate false, the plugin will be running "headless" without your Application code. If you wish for your Flutter Application to boot as well, you may configure any of the following forceReloadOnXXX options:

ℹ️ See also:

Optional stationaryRadius

stationaryRadius: number

[iOS only] The minimum distance the device must move beyond the stationary location for aggressive background-tracking to engage.

⚠️ Note: iOS will not detect the exact moment the device moves out of the stationary-radius. In normal conditions, it will typically

take ~200 meters of movement before the plugin begins tracking.

break

Configuring stationaryRadius: 0 has NO EFFECT. In fact the plugin enforces a minimum stationaryRadius of 25 and in-practice, the native API won't respond for at least 200 meters.

The following image shows the typical distance iOS requires to detect exit of the stationaryRadius:

  • Green polylines: represent a transition from stationary state to moving (~200 meters).
  • Red circles: locations where the plugin entered the stationary state.

ℹ️ See also:

Optional stopAfterElapsedMinutes

stopAfterElapsedMinutes: number

Automatically stop tracking after x minutes.

The plugin can optionally automatically stop after some number of minutes elapses after the start method was called.

example
BackgroundGeolocation.ready({
  stopAfterElapsedMinutes: 30
}).then((state) => {
  BackgroundGeolocation.start();  // <-- plugin will automatically #stop in 30 minutes
});

Optional stopDetectionDelay

stopDetectionDelay: number

[iOS only] Allows the iOS stop-detection system to be delayed from activating.

break

Defaults to 0 (no delay). Allows the stop-detection system to be delayed from activating. When the stop-detection system is engaged, location-services will be temporarily turned off and only the accelerometer is monitored. Stop-detection will only engage if this timer expires. The timer is cancelled if any movement is detected before expiration. If a value of 0 is specified, the stop-detection system will engage as soon as the device is detected to be stationary.

You can experience the iOS stop-detection system at work by configuring debug true. After the device stops moving (stopped at a traffic light, for example), the plugin will emit a Lullabye sound-effect and local-notifications about "Location-services: OFF / ON".

iOS Stop-detection timing

Optional stopOnStationary

stopOnStationary: boolean

Automatically BackgroundGeolocation.stop when the stopTimeout elapses.

break

The plugin can optionally automatically stop tracking when the stopTimeout timer elapses. For example, when the plugin first fires BackgroundGeolocation.onMotionChange into the moving state, the next time an onMotionChange event occurs into the stationary state, the plugin will have automatically called BackgroundGeolocation.stop upon itself.

⚠️ stopOnStationary will only occur due to stopTimeout timer elapse. It will not occur by manually executing BackgroundGeolocation.changePace false.

example
BackgroundGeolocation.ready({
  stopOnStationary: true,
  isMoving: true
}, (state) => {
  BackgroundGeolocation.start();
});

Optional stopOnTerminate

stopOnTerminate: boolean

Controls whether to continue location-tracking after application is terminated.

break

Defaults to true. When the user terminates the app, the plugin will BackgroundGeolocation.stop tracking. Set this to false to continue tracking after application terminate.

If you do configure stopOnTerminate: false, your application will terminate at that time. However, both Android and iOS differ in their behaviour after this point:

iOS

Before an iOS app terminates, the plugin will ensure that a stationary geofence of stationaryRadius meters is created around the last known position. When the user moves beyond the stationary geofence (typically ~200 meters), iOS will completely reboot your application in the background, and the plugin will resume tracking. iOS maintains geofence monitoring at the OS level, in spite of application terminate / device reboot.

In the following image, imagine the user terminated the application at the "red circle" on the right, then continued moving: Once the device moves by about 200 meters, exiting the "stationary geofence", iOS reboots the app and tracking resumes.

ℹ️ Demo Video of stopOnTerminate: false

Android

Unlike iOS, the Android plugin's tracking will not pause at all when user terminates the app. However, only the plugin's native background service continues to operate, "headless" (in this case, you should configure an url in order for the background-service to continue uploading locations to your server).

ℹ️ See also:

Optional stopTimeout

stopTimeout: number

Minutes to wait in moving state with no movement before considering the device stationary.

break

Defaults to 5 minutes. When in the moving state, specifies the number of minutes to wait before turning off location-services and transitioning to stationary state after the ActivityRecognition System detects the device is STILL. An example use-case for this configuration is to delay GPS OFF while in a car waiting at a traffic light.

ℹ️ See also:

Optional triggerActivities

triggerActivities: string

[Android-only] Configures a comma-separated list of motion-activities which are allow to trigger location-tracking.

break

These are the comma-delimited list of activity-names returned by the ActivityRecognition API which will trigger a state-change from stationary to moving. By default, the plugin will trigger on any of the moving-states:

Activity Name
in_vehicle
on_bicycle
on_foot
running
walking

If you wish, you can configure the plugin to only engage the moving state for vehicles-only by providing just "in_vehicle", for example.

example
// Only trigger tracking for vehicles
BackgroundGeolocation.ready({
  triggerActivities: 'in_vehicle'
);

// Only trigger tracking for on_foot, walking and running
BackgroundGeolocation.ready({
  triggerActivities: 'on_foot, walking, running'
);

Optional url

url: string

Your server url where you wish the SDK to automatically upload location data.

example
BackgroundGeolocation.ready({
  url: 'https://my-server.com/locations'
});

You can observe the plugin performing HTTP requests in the logs for both iOS and Android (See Wiki Debugging):

example
╔═════════════════════════════════════════════
β•‘ LocationService: location
╠═════════════════════════════════════════════
β•Ÿβ”€ πŸ“ Location[45.519199,-73.617054]
βœ… INSERT: 70727f8b-df7d-48d0-acbd-15f10cacdf33
╔═════════════════════════════════════════════
β•‘ HTTP Service
╠═════════════════════════════════════════════
βœ… Locked 1 records
πŸ”΅ HTTP POST: 70727f8b-df7d-48d0-acbd-15f10cacdf33
πŸ”΅ Response: 200
βœ… DESTROY: 70727f8b-df7d-48d0-acbd-15f10cacdf33
# Log entry Description
1 πŸ“Location Location received from native Location API.
2 βœ…INSERT Location record inserted into SDK's SQLite database.
3 βœ…Locked SDK's HTTP service locks a record (to prevent duplicate HTTP uploads).
4 πŸ”΅HTTP POST SDK's HTTP service attempts an HTTP request to your configured url.
5 πŸ”΅Response Response from your server.
6 βœ…DESTROY|UNLOCK After your server returns a 20x response, the SDK deletes that record from it SQLite database. Otherwise, the SDK will UNLOCK that record and try again in the future.

HTTP Failures

If your server does not return a 20x response (eg: 200, 201, 204), the SDK will UNLOCK that record. Another attempt to upload once again in the future until maxDaysToPersist:

  • When another location is recorded.
  • Application pause / resume events.
  • Application boot.
  • onHeartbeat events.
  • onConnectivityChange events.
  • [iOS] Background fetch events.

⚠️ Note:

It is highly recommended to let the plugin manage uploading locations to your server, particularly for Android when configured with stopOnTerminate: false, since MainActivity (where your application code lives) will terminate — only the plugin's native Android background service will continue to operate, recording locations and uploading to your server. The SDK's native HTTP service is better at this task, since the SDK will automatically retry on server failure.

ℹ️ See also:

Optional useSignificantChangesOnly

useSignificantChangesOnly: boolean

[iOS only] Engages iOS "significant location changes" API for only periodic location updates every 500-1000 meters.

break

Defaults to false. Set true in order to disable constant background-tracking and use only the iOS Significant Changes API.

⚠️ If Apple has rejected your application, refusing to grant your app the privelege of using the UIBackgroundMode: "location", this can be a solution.

ℹ️ The Significant Changes API will report a location only every 500 to 1000 meters (can be higher in non urban environments; depends upon the spacing of Cellular towers). Many of the plugin's configuration parameters will be ignored, such as distanceFilter, stationaryRadius, activityType, etc.

Generated using TypeDoc