Primary API of the SDK.

break

📚 Help

⚡ī¸ Events

BackgroundGeolocation is event-based. Interacting with the SDK is largely through implementing listeners on the following events:

Method Description
onLocation Fired with each recorded Location
onMotionChange Fired when the plugin changes state between moving / stationary
onHttp Fired with each HTTP response from your server. (see url).
onActivityChange Fired with each change in device motion-activity.
onProviderChange Fired after changes to device location-services configuration.
onHeartbeat Periodic timed events. See heartbeatInterval. iOS requires preventSuspend.
onGeofence Fired with each Geofence transition event (ENTER, EXIT, DWELL).
onGeofencesChange Fired when the list of actively-monitored geofences changed. See geofenceProximityRadius.
onSchedule Fired for schedule events.
onConnectivityChange Fired when network-connectivity changes (connected / disconnected).
onPowerSaveChange Fired when state of operating-system's "power-saving" feature is enabled / disabld.
onEnabledChange Fired when the plugin is enabled / disabled via its start / stop methods.

🔧 Config API

BackgroundGeolocation is highly configurable. See the Config API for more information.

There are three main steps to using BackgroundGeolocation

  1. Wire up event-listeners.
  2. ready the SDK.
  3. start tracking.
example

////
// 1.  Wire up event-listeners
//

// This handler fires whenever bgGeo receives a location update.
BackgroundGeolocation.onLocation(location => {
  console.log('[location] ', location);
}, error => {
  console.log('[location] ERROR: ', error);
});

// This handler fires when movement states changes (stationary->moving; moving->stationary)
BackgroundGeolocation.onMotionChange(location => {
  console.log('[motionchange] ', location);
});

// This handler fires on HTTP responses
BackgroundGeolocation.onHttp(response => {
  console.log('[http] ', response);
});

// This event fires when a change in motion activity is detected
BackgroundGeolocation.onActivityChange(activityEvent => {
  console.log('[activitychange] ', activityEvent);
});

// This event fires when the user toggles location-services authorization
BackgroundGeolocation.onProviderChange(providerEvent => {
  console.log('[providerchange] ', providerEvent);
});

////
// 2.  Execute #ready method (required)
//
BackgroundGeolocation.ready({
  // Geolocation Config
  desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
  distanceFilter: 10,
  // Activity Recognition
  stopTimeout: 1,
  // Application config
  debug: true,              // <-- enable this hear debug sounds.
  logLevel: BackgroundGeolocation.LOG_LEVEL_VERBOSE,
  stopOnTerminate: false,   // <-- Allow the background-service to continue tracking when app terminated.
  startOnBoot: true,        // <-- Auto start tracking when device is powered-up.
  // HTTP / SQLite config
  url: 'http://yourserver.com/locations',
  batchSync: false,       // <-- Set true to sync locations to server in a single HTTP request.
  autoSync: true,         // <-- Set true to sync each location to server as it arrives.
  headers: {              // <-- Optional HTTP headers
    "X-FOO": "bar"
  },
  params: {               // <-- Optional HTTP params
    "auth_token": "maybe_your_server_authenticates_via_token_YES?"
  }
}, (state) => {
  console.log("- BackgroundGeolocation is configured and ready: ", state.enabled);

  if (!state.enabled) {
    ////
    // 3. Start tracking!
    //
    BackgroundGeolocation.start(function() {
      console.log("- Start success");
    });
  }
});

ℹī¸ Note:

The configuration {} provided to the ready method is applied only when your app is first booted — for every launch thereafter, the plugin will automatically load the last known configuration from persistant storage. If you wish to force the #ready method to always apply the supplied config {}, you can specify reset: true

example
BackgroundGeolocation.ready({
  reset: true,  // <-- true to always apply the supplied config
  distanceFilter: 10
}, (state) => {
  console.log('- BackgroundGeolocation is ready: ', state);
});

⚠ī¸ 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.)

example
// Traditional API still works:
BackgroundGeolocation.ready({desiredAccuracy: 0, distanceFilter: 50}).then(state => {
  console.log('- BackgroundGeolocation is ready: ', state);
}).catch(error => {
  console.log('- BackgroundGeolocation error: ', error);
});

Hierarchy

  • BackgroundGeolocation

Index

Events

Static onActivityChange

  • onActivityChange(callback: function): void
  • 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).

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

    Parameters

    Returns void

Static onConnectivityChange

  • onConnectivityChange(callback: function): void
  • 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.

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

    Parameters

    Returns void

Static onEnabledChange

  • onEnabledChange(callback: function): void
  • Subscribe to changes in plugin State.enabled.

    Fired when the plugin's State.enabled changes. For example, executing start and stop will cause the onEnabledChnage event to fire. This event is primarily desigend for use with the configuration option stopAfterElapsedMinutes, which automatically executes the plugin's stop method.

    example
    BackgroundGeolocation.onEnabledChange(isEnabled => {
      console.log('[onEnabledChanged] isEnabled? ', isEnabled);
    });

    Parameters

    • callback: function
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    Returns void

Static onGeofence

  • onGeofence(callback: function): void
  • Subscribe to Geofence transition events.

    Your supplied callback will be called when any monitored geofence crossing occurs.

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

    ℹī¸ See also:

    Parameters

    Returns void

Static onGeofencesChange

  • onGeofencesChange(callback: function): void
  • 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.

    example
    BackgroundGeolocation.onGeofencesChange((event) => {
      let on = event.on;     //<-- new geofences activiated.
      let off = event.off; //<-- geofences that were just de-activated.
    
      // Create map circles
      on.forEach((geofence) => {
        createGeofenceMarker(geofence)
      });
    
      // Remove map circles
      off.forEach((identifier) => {
        removeGeofenceMarker(identifier);
      }
    });

    ℹī¸ See also:

    Parameters

    Returns void

Static onHeartbeat

  • onHeartbeat(callback: function): void
  • 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).

    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);
      });
    })

    ⚠ī¸ Note:

    • The Location provided by the HeartbeatEvent is only the last-known location. The heartbeat event does not actively engage location-services. If you wish to get the current location in your callback, use getCurrentPosition.

    Parameters

    Returns void

Static onHttp

  • onHttp(callback: function): void
  • Subscribe to HTTP responses from your server url.

    example
    BackgroundGeolocation.onHttp((event) => {
      let status = response.status;
      let success = response.success;
      let responseText = response.responseText;
      console.log('[onHttp] ', event);
    });

    ℹī¸ See also:

    Parameters

    • callback: function

    Returns void

Static onLocation

  • onLocation(success: function, failure?: function): void
  • Subscribe to location events.

    Every location recorded by the SDK is provided to your callback, including those from onMotionChange, getCurrentPosition and watchPosition.

    example
    BackgroundGeolocation.onLocation((location) => {
      console.log('[onLocation] success: ', location);
    }, (error) => {
      console.log('[onLocation] ERROR: ', error);
    });

    Error Codes

    If the native location API fails to return a location, the failure callback will be provided a LocationError.

    ⚠ī¸ Note Location.sample:

    When performing a onMotionChange or getCurrentPosition, the plugin requests multiple location samples in order to record the most accurate location possible. These samples are not persisted to the database but they will be provided to your callback, for your convenience, since it can take some seconds for the best possible location to arrive.

    For example, you might use these samples to progressively update the user's position on a map. You can detect these samples in your callback via location.sample == true. If you're manually POSTing location to your server, you should ignore these locations.

    Parameters

    Returns void

Static onMotionChange

  • onMotionChange(callback: function): void
  • Subscribe to motionchange events.

    Your callback will be executed each time the device has changed-state between MOVING or STATIONARY.

    example
    BackgroundGeolocation.onMotionChange((event) => {
      if (event.isMoving) {
         console.log('[onMotionChange] Device has just started MOVING ', event.location);
      } else {
         console.log('[onMotionChange] Device has just STOPPED:  ', event.location);
      }
    });

    ℹī¸ See also:

    Parameters

    Returns void

Static onPowerSaveChange

  • onPowerSaveChange(callback: function): void
  • Subsribe 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.

    break

    ℹī¸ You can manually request the current-state of "Power Saving" mode with the method isPowerSaveMode.

    iOS

    iOS Power Saving mode can be engaged manually by the user in Settings -> Battery or from an automatic OS dialog.

    Android

    Android Power Saving mode can be engaged manually by the user in Settings -> Battery -> Battery Saver or automatically with a user-specified "threshold" (eg: 15%).

    example
    BackgroundGeolocation.oPowerSaveChange((isPowerSaveMode) => {
      console.log('[onPowerSaveChange: ', isPowerSaveMode);
    });

    Parameters

    • callback: function
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    Returns void

Static onProviderChange

  • onProviderChange(callback: function): void
  • 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".

    example
    BackgroundGeolocation.onProviderChange((event) => {
      console.log('[onProviderChange: ', event);
    
      switch(event.status) {
        case BackgroundGeolocation.AUTHORIZATION_STATUS_DENIED:
          // Android & iOS
          console.log('- Location authorization denied');
          break;
        case BackgroundGeolocation.AUTHORIZATION_STATUS_ALWAYS:
          // Android & iOS
          console.log('- Location always granted');
          break;
        case BackgroundGeolocation.AUTHORIZATION_STATUS_WHEN_IN_USE:
          // iOS only
          console.log('- Location WhenInUse granted');
          break;
      }
    });

    ⚠ī¸ Note:

    • The plugin always force-fires an onProviderChange event whenever the app is launched (right after the ready method is executed), regardless of current state, so you can learn the the current state of location-services with each boot of your application.

    Parameters

    Returns void

Static onSchedule

  • onSchedule(callback: function): void
  • 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.

    example
    BackgroundGeolocation.onSchedule((state) => {
      if (state.enabled) {
        console.log('[onSchedule] scheduled start tracking');
      } else {
        console.log('[onSchedule] scheduled stop tracking');
      }
    });

    Parameters

    • callback: function
        • Parameters

          Returns void

    Returns void

Properties

Static ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION

ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION: ActivityType

Static ACTIVITY_TYPE_FITNESS

ACTIVITY_TYPE_FITNESS: ActivityType

Static ACTIVITY_TYPE_OTHER

ACTIVITY_TYPE_OTHER: ActivityType

Static ACTIVITY_TYPE_OTHER_NAVIGATION

ACTIVITY_TYPE_OTHER_NAVIGATION: ActivityType

Static AUTHORIZATION_STATUS_ALWAYS

AUTHORIZATION_STATUS_ALWAYS: AuthorizationStatus

Static AUTHORIZATION_STATUS_DENIED

AUTHORIZATION_STATUS_DENIED: AuthorizationStatus

Static AUTHORIZATION_STATUS_NOT_DETERMINED

AUTHORIZATION_STATUS_NOT_DETERMINED: AuthorizationStatus

Static AUTHORIZATION_STATUS_RESTRICTED

AUTHORIZATION_STATUS_RESTRICTED: AuthorizationStatus

Static AUTHORIZATION_STATUS_WHEN_IN_USE

AUTHORIZATION_STATUS_WHEN_IN_USE: AuthorizationStatus

Static DESIRED_ACCURACY_HIGH

DESIRED_ACCURACY_HIGH: LocationAccuracy

Static DESIRED_ACCURACY_LOW

DESIRED_ACCURACY_LOW: LocationAccuracy

Static DESIRED_ACCURACY_LOWEST

DESIRED_ACCURACY_LOWEST: LocationAccuracy

Static DESIRED_ACCURACY_MEDIUM

DESIRED_ACCURACY_MEDIUM: LocationAccuracy

Static DESIRED_ACCURACY_NAVIGATION

DESIRED_ACCURACY_NAVIGATION: LocationAccuracy

Static DESIRED_ACCURACY_VERY_LOW

DESIRED_ACCURACY_VERY_LOW: LocationAccuracy

Static LOG_LEVEL_DEBUG

LOG_LEVEL_DEBUG: LogLevel

Static LOG_LEVEL_ERROR

LOG_LEVEL_ERROR: LogLevel

Static LOG_LEVEL_INFO

LOG_LEVEL_INFO: LogLevel

Static LOG_LEVEL_OFF

LOG_LEVEL_OFF: LogLevel

Static LOG_LEVEL_VERBOSE

LOG_LEVEL_VERBOSE: LogLevel

Static LOG_LEVEL_WARNING

LOG_LEVEL_WARNING: LogLevel

Static NOTIFICATION_PRIORITY_DEFAULT

NOTIFICATION_PRIORITY_DEFAULT: NotificationPriority

Static NOTIFICATION_PRIORITY_HIGH

NOTIFICATION_PRIORITY_HIGH: NotificationPriority

Static NOTIFICATION_PRIORITY_LOW

NOTIFICATION_PRIORITY_LOW: NotificationPriority

Static NOTIFICATION_PRIORITY_MAX

NOTIFICATION_PRIORITY_MAX: NotificationPriority

Static NOTIFICATION_PRIORITY_MIN

NOTIFICATION_PRIORITY_MIN: NotificationPriority

Static logger

logger: Logger

Methods

Static addGeofence

  • addGeofence(config: Geofence, success?: Function, failure?: function): Promise<void>
  • Adds a Geofence to be monitored by the native Geofencing API.

    example
    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');
    }).catchError((error) => {
      console.log('[addGeofence] FAILURE: ', error);
    });

    ℹī¸ Note:

    • If a geofence(s) already exists with the configured Geofence.identifier, the previous one(s) will be deleted before the new one is inserted.
    • When adding multiple, it's about 10 times faster to use addGeofences instead.
    • 📘Geofence Guide.

    Parameters

    • config: Geofence
    • Optional success: Function
    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static addGeofences

  • addGeofences(geofences: Array<Geofence>, success?: Function, failure?: Function): Promise<void>
  • Adds a list of Geofence to be monitored by the native Geofencing API.

    example
    let 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);

    ℹī¸ Note:

    Parameters

    • geofences: Array<Geofence>
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static changePace

  • changePace(isMoving: boolean, success?: Function, failure?: function): Promise<void>
  • Manually toggles the plugin'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.

    example
    BackgroundGeolocation.changePace(true);  // <-- Location-services ON ("moving" state)
    BackgroundGeolocation.changePace(false); // <-- Location-services OFF ("stationary" state)

    Parameters

    • isMoving: boolean
    • Optional success: Function
    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static destroyLocations

  • destroyLocations(success?: Function, failure?: Function): Promise<void>
  • Remove all records in plugin's SQLite database.

    example
    let success = await BackgroundGeolocation.destroyLocations();

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static destroyLog

  • destroyLog(success?: Function, failure?: Function): Promise<void>
  • Destory the entire contents of plugin's log database.

    example
    BackgroundGeolocation.destroyLog();

    ℹī¸ See also:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static emailLog

  • emailLog(email: string, success?: Function, failure?: function): Promise<void>
  • Email the result of getLog using device's mail client.

    example
    BackgroundGeolocation.emailLog('foo@bar.com').then((success) => {
      console.log('[emailLog] success');
    }).catchError((error) => {
      console.log('[emailLog] FAILURE: ', error);
    });

    ℹī¸ See also:

    Parameters

    • email: string
    • Optional success: Function
    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<void>

Static finish

  • finish(taskId: number, success?: Function, failure?: Function): Promise<void>
  • Signal completion of startBackgroundTask

    Sends a signal to the native OS that your long-running task, addressed by taskId privided by startBackgroundTask is complete and the OS may proceed to suspend your application if applicable.

    example
    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.finish(taskId);
      });
    });

    Parameters

    • taskId: number
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static getCount

  • getCount(success?: function, failure?: Function): Promise<number>
  • Retrive the count of all locations current stored in the plugin's SQLite datbase.

    example
    let count = await BackgroundGeolocation.getCount();

    Parameters

    • Optional success: function
        • (count: number): void
        • Parameters

          • count: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static getCurrentPosition

  • 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 url. If an error occurs while fetching the location, catchError will be provided with an LocationError.

    break

    Options

    See CurrentPositionRequest.

    Error Codes

    See LocationError.

    example
    let 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
      }
    });

    ⚠ī¸ Note:

    Parameters

    Returns Promise<Location>

Static getGeofences

  • getGeofences(success?: function, failure?: function): Promise<Array<Geofence>>
  • Fetch a list of all Geofence in the SDK's database. If there are no geofences being monitored, you'll receive an empty Array.

    example
    let geofences = await BackgroundGeolocation.getGeofences();
    console.log('[getGeofences: ', geofences);

    ℹī¸ See also:

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<Array<Geofence>>

Static getLocations

  • getLocations(success?: function, failure?: Function): Promise<Array<Object>>
  • Retrive a List of Location currently stored in the plugin's SQLite datbase.

    example
    let locations = await BackgroundGeolocation.getLocations();

    Parameters

    • Optional success: function
        • (locations: Array<Object>): void
        • Parameters

          • locations: Array<Object>

          Returns void

    • Optional failure: Function

    Returns Promise<Array<Object>>

Static getLog

  • getLog(success?: function, failure?: function): Promise<string>
  • Returns the entire contents of the log database.

    break

    Depending on the configured logLevel, the plugin can store an immense amount of helpful logging information for debugging location-tracking problems.

    ℹī¸ See also:

    example
    BackgroundGeolocation.getLog.then((log) => {
      // Warning:  this string could be several megabytes.
      console.log('[log] success: ', log);
    });
    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%)

    Parameters

    • Optional success: function
        • (log: string): void
        • Parameters

          • log: string

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<string>

Static getOdometer

  • getOdometer(success?: function, failure?: Function): Promise<number>
  • Retrieve the current distance-travelled ("odometer").

    The plugin constantly tracks distance travelled, computing the distance between the current location and last and maintaining the sum. To fetch the current odometer reading:

    example
    let odometer = await BackgroundGeolocation.getOdometer();

    ℹī¸ See also:

    ⚠ī¸ Warning:

    • Odometer calculations are dependant upon the accuracy of received locations. If location accuracy is poor, this will necessarily introduce error into odometer calculations.

    Parameters

    • Optional success: function
        • (odometer: number): void
        • Parameters

          • odometer: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static getSensors

  • getSensors(success?: function, failure?: Function): Promise<Sensors>
  • Returns the presense of device sensors accelerometer, gyroscope, magnetometer

    break

    These core Sensors are used by the motion activity-recognition system -- when any of these sensors are missing from a device (particularly on cheap Android devices), the performance of the motion activity-recognition system will be severely degraded and highly inaccurate.

    For devices which are missing any of these sensors, you can increase the motion-detection sensitivity by decreasing minimumActivityRecognitionConfidence.

    example
    let sensors = await BackgroundGeolocation.sensors;
    console.log(sensors);

    Parameters

    • Optional success: function
    • Optional failure: Function

    Returns Promise<Sensors>

Static getState

  • getState(success?: function, failure?: function): Promise<State>
  • Return the current State of the plugin, including all Config parameters.

    example
    let state = await BackgroundGeolocation.state();
    console.log('[state] ', state.enabled, state.trackingMode);

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static insertLocation

  • insertLocation(params: Location, success?: function, failure?: Function): Promise<Location>
  • Parameters

    • params: Location
    • Optional success: function
    • Optional failure: Function

    Returns Promise<Location>

Static isPowerSaveMode

  • isPowerSaveMode(success?: function, failure?: Function): Promise<boolean>
  • Fetches the state of the operating-system's "Power Saving" mode.

    break

    Power Saving mode can throttle certain services in the background, such as HTTP requests or GPS.

    ℹī¸ You can listen to changes in the state of "Power Saving" mode from the event onPowerSaveChange.

    iOS

    iOS Power Saving mode can be engaged manually by the user in Settings -> Battery or from an automatic OS dialog.

    Android

    Android Power Saving mode can be engaged manually by the user in Settings -> Battery -> Battery Saver or automatically with a user-specified "threshold" (eg: 15%).

    example
    let isPowerSaveMode = await BackgroundGeolocation.isPowerSaveMode;

    Parameters

    • Optional success: function
        • (enabled: boolean): void
        • Parameters

          • enabled: boolean

          Returns void

    • Optional failure: Function

    Returns Promise<boolean>

Static playSound

  • playSound(soundId: number, success?: Function, failure?: Function): Promise<void>
  • Parameters

    • soundId: number
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static ready

  • ready(config: Config, success?: function, failure?: function): Promise<State>
  • 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 persisent storage. The plugin always remembers the configuration you apply to it.

    example
    BackgroundGeolocation.ready({
      desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_HIGH,
      distanceFilter: 10,
      stopOnTerminate: false,
      startOnBoot: true,
      url: 'http://your.server.com',
      headers: {
       'my-auth-token': 'secret-token'
      }
    }).then((state) => {
     console.log('[ready] success', state);
    });

    ⚠ī¸ Note:

    The #ready method only applies the supplied Config for the first launch of the app — forever after, the plugin is going to remember every configuration change you apply at runtime (eg: setConfig) and reload that same config every time your app boots. Changes to the Config supplied to ready after first launch will not take effect. During development, it's helpful to provide reset true.

    The reset method.

    If you wish, you can use the reset method to reset all Config options to documented default-values (with optional overrides):

    example
    BackgroundGeolocation.reset();
    // Reset to documented default-values with overrides
    bgGeo.reset({
      distanceFilter:  10
    });

    reset: true

    Optionally, you can set reset to true This is helpful during development. 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
    }).then((state) => {
      console.log('[ready]', state)
    });

    Parameters

    • config: Config
    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static registerHeadlessTask

  • registerHeadlessTask(callback: function): void
  • 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).

    ⚠ī¸ Note Cordova

    • Javascript headless callbacks are not supported by Cordova.

    ⚠ī¸ Warning:

    • You must registerHeadlessTask in your application root file (eg: index.js).
    example
    let BackgroundGeolocationHeadlessTask = async (event) => {
      let params = event.params;
       console.log('[BackgroundGeolocation HeadlessTask] -', event.name, params);
    
       switch (event.name) {
         case 'heartbeat':
           // Use await for async tasks
           let location = await BackgroundGeolocation.getCurrentPosition({
             samples: 1,
             persist: false
           });
           console.log('[BackgroundGeolocation HeadlessTask] - getCurrentPosition:', location);
           break;
       }
    }
    
    BackgroundGeolocation.registerHeadlessTask(BackgroundGeolocationHeadlessTask);

    ℹī¸ See also:

    Parameters

    • callback: function
        • (event: Object): any
        • Parameters

          • event: Object

          Returns any

    Returns void

Static removeAllListeners

  • removeAllListeners(success?: Function, failure?: Function): void
  • Alias for removeListeners

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns void

Static removeGeofence

  • removeGeofence(identifier: string, success?: Function, failure?: Function): Promise<void>
  • Removes a Geofence having the given Geofence.identifier.

    example
    BackgroundGeolocation.removeGeofence("Home").then((success) => {
      console.log('[removeGeofence] success');
    }).catchError((error) => {
      console.log('[removeGeofence] FAILURE: ', error);
    });

    ℹī¸ See also:

    Parameters

    • identifier: string
    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static removeGeofences

  • removeGeofences(success?: Function, failure?: Function): Promise<void>
  • Destroy all Geofence.

    example
    BackgroundGeolocation.removeGeofences();

    ℹī¸ See also:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static removeListener

  • removeListener(event: string, handler: Function, success?: Function, failure?: Function): void
  • Removes an event listener. You must supply the type of event to remove in addition to a reference to the exact function you used to subscribe to the event.

    Event
    location
    motionchange
    activitychange
    providerchange
    geofence
    geofenceschange
    heartbeat
    http
    powersavechange
    schedule
    connectivitychange
    enabledchange
    example
    let locationHandler = (location) => {
      console.log('[location] - ', location)
    }
    BackgroundGeolocation.onLocation(locationHandler)
    .
    .
    // Remove the listener providing a reference to the original callback.
    BackgroundGeolocation.removeListener('location', locationHandler)

    Parameters

    • event: string
    • handler: Function
    • Optional success: Function
    • Optional failure: Function

    Returns void

Static removeListeners

  • removeListeners(success?: Function, failure?: Function): void
  • Removes all event-listeners

    example
    BackgroundGeolocation.removeListeners();

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns void

Static reset

  • reset(config?: Config, success?: function, failure?: Function): Promise<State>
  • Resets the plugin configuration to documented default-values.

    If an optional Config is provided, it will be applied after the configuration reset.

    Parameters

    • Optional config: Config
    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static resetOdometer

  • resetOdometer(success?: Function, failure?: Function): Promise<Location>
  • Initialize the odometer to 0.

    example
    BackgroundGeolocation.resetOdometer().then((location) => {
      // This is the location where odometer was set at.
      console.log('[setOdometer] success: ', location);
    });

    ⚠ī¸ Note:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<Location>

Static setConfig

  • setConfig(config: Config, success?: function, failure?: Function): Promise<State>
  • Re-configure the plugin'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.

    example
    BackgroundGeolocation.setConfig({
      desiredAccuracy: Config.DESIRED_ACCURACY_HIGH,
      distanceFilter: 100.0,
      stopOnTerminate: false,
      startOnBoot: true
    }).then((state) => {
      console.log('[setConfig] success: ', state);
    })

    Parameters

    • config: Config
    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static setLogLevel

  • setLogLevel(value: LogLevel, success?: function, failure?: Function): Promise<State>
  • Sets the logLevel.

    Parameters

    • value: LogLevel
    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: Function

    Returns Promise<State>

Static setOdometer

  • setOdometer(value: number, success?: function, failure?: Function): Promise<Location>
  • Initialize the odometer to any arbitrary value.

    example
    BackgroundGeolocation.setOdometer(1234.56).then((location) => {
      // This is the location where odometer was set at.
      console.log('[setOdometer] success: ', location);
    });

    ⚠ī¸ Note:

    Parameters

    • value: number
    • Optional success: function
    • Optional failure: Function

    Returns Promise<Location>

Static start

  • start(success?: function, error?: function): Promise<State>
  • Enable location + geofence tracking.

    This is the plugin'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.

    ⚠ī¸ Note:

    If you've configured a schedule, this method will override that schedule and engage tracking immediately.

    example
    BackgroundGeolocation.start().then((state) => {
      console.log('[start] success - ', state);
    });

    ℹī¸ See also:

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional error: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static startBackgroundTask

  • startBackgroundTask(success?: function, failure?: Function): Promise<number>
  • Sends a signal to iOS that you wish to perform a long-running task.

    iOS will not suspend your app until you signal completion with the finish method. Your callback will be provided with a single parameter taskId which you will send to the finish method.

    example
    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.finish(taskId);
      });
    });

    ⚠ī¸ iOS provides exactly 180s of background-running time. If your long-running task exceeds this time, the plugin has a fail-safe which will automatically finish your taskId to prevent the OS from force-killing your application.

    Parameters

    • Optional success: function
        • (taskId: number): void
        • Parameters

          • taskId: number

          Returns void

    • Optional failure: Function

    Returns Promise<number>

Static startGeofences

  • startGeofences(success?: function, failure?: function): Promise<State>
  • 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.

    example
    // 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 the plugin
    BackgroundGeolocation.ready({
      url: 'http://my.server.com',
      autoSync: true
    }).then(((state) => {
      // Start monitoring geofences.
      BackgroundGeolocation.startGeofences();
    });

    ℹī¸ See also:

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static startSchedule

  • startSchedule(success?: function, failure?: function): Promise<State>
  • 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.

    example
    BackgroundGeolocation.startSchedule.then((state) => {
      console.log('[startSchedule] success: ', state);
    })

    ℹī¸ See also:

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stop

  • stop(success?: function, error?: function): Promise<State>
  • Disable location and geofence monitoring. This is the SDK's power OFF button.

    example
    BackgroundGeolocation.stop();

    ⚠ī¸ Note:

    If you've configured a schedule, #stop will not halt the Scheduler. You must explicitly stopSchedule as well:

    example
    // Later when you want to stop the Scheduler (eg: user logout)
    BackgroundGeolocation.stopSchedule();

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional error: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stopSchedule

  • stopSchedule(success?: function, failure?: function): Promise<State>
  • Halt scheduled tracking.

    example
    BackgroundGeolocation.stopSchedule.then((state) => {
      console.log('[stopSchedule] success: ', state);
    })

    ⚠ī¸ stopSchedule will not execute stop if the plugin is currently tracking. You must explicitly execute stop.

    example
    // Later when you want to stop the Scheduler (eg: user logout)
    await BackgroundGeolocation.stopSchedule().then((state) => {
      if (state.enabled) {
        BackgroundGeolocation.stop();
      }
    })

    ℹī¸ See also:

    Parameters

    • Optional success: function
        • Parameters

          Returns void

    • Optional failure: function
        • (error: string): void
        • Parameters

          • error: string

          Returns void

    Returns Promise<State>

Static stopWatchPosition

  • stopWatchPosition(success?: Function, failure?: Function): Promise<void>
  • Stop watch-position updates initiated from watchPosition.

    example
    onResume() {
      // Start watching position while app in foreground.
      BackgroundGeolocation.watchPosition((location) => {
        console.log('[watchPosition] -', location);
      }, (errorCode) => {
        console.log('[watchPosition] ERROR -', errorCode);
      }, {
       interval: 1000
      })
    }
    
    onSuspend() {
      // Halt watching position when app goes to background.
      BackgroundGeolocation.stopWatchPosition();
    }

    ℹī¸ See also:

    Parameters

    • Optional success: Function
    • Optional failure: Function

    Returns Promise<void>

Static sync

  • sync(success?: function, failure?: Function): Promise<Array<Object>>
  • Manually execute upload to configured url

    If the plugin is configured for HTTP with an url and autoSync false, the sync method will initiate POSTing the locations currently stored in the native SQLite database to your configured 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 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 datbase.

    example
    BackgroundGeolocation.sync((records) => {
      console.log('[sync] success: ', records);
    }).catchError((error) => {
      console.log('[sync] FAILURE: ', error);
    });
    

    ℹī¸ For more information, see the HTTP Guide at HttpEvent.

    Parameters

    • Optional success: function
        • (locations: Array<Object>): void
        • Parameters

          • locations: Array<Object>

          Returns void

    • Optional failure: Function

    Returns Promise<Array<Object>>

Static transistorTrackerParams

  • transistorTrackerParams(device: Object): Object
  • Convenience method to compose a params Object suitable for posting to the Transistor Software Test Server at http://tracker.transistorsoft.com. You must provide a reference to Device instance.

    Cordova

    • Provide an instance of cordova-plugin-device (Ionic: @ionic-native/device).

    React Native

    • Provide an instance of react-native-device-info

    The test server is a great way to debug location problems, since the results can easily be shared with Transistor Software when requesting support.

    example
    BackgroundGeolocation.ready({
      url: 'http://tracker.transistorsoft.com/locations/my-username',
      params: BackgroundGeolocation.transistorTrackerParams(device)
    })

    ⚠ī¸ Note:

    • To view your tracking results in the browser, the url is just /YOUR-USERNAME — not /locations/YOUR-USERNAME

    Parameters

    • device: Object

    Returns Object

Static watchPosition

  • 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 enabled) in addition to POSTing to your configured url (if you've enabled the HTTP features).

    ⚠ī¸ Warning:

    watchPosition is not reccommended 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.

    iOS

    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.

    example
    onResume() {
      // Start watching position while app in foreground.
      BackgroundGeolocation.watchPosition((location) => {
        console.log('[watchPosition] -', location);
      }, (errorCode) => {
        console.log('[watchPosition] ERROR -', errorCode);
      }, {
        interval: 1000
      })
    }
    
    onSuspend() {
      // Halt watching position when app goes to background.
      BackgroundGeolocation.stopWatchPosition();
    }

    Parameters

    Returns void

Generated using TypeDoc