react-native-background-geolocation@5.0.0-beta.1
    Preparing search index...

    Interface BackgroundGeolocation

    Primary BackgroundGeolocation API

    Overview

    The BackgroundGeolocation interface defines the complete, strongly-typed API surface for Transistor Software’s Background Geolocation SDK.
    This is the main entry-point used by all JavaScript adapters:

    • React Native (react-native-background-geolocation)
    • Capacitor
    • Cordova

    The API provides:

    • Configuration via a single Config object composed of modular sub-configs (GeoConfig, HttpConfig, PersistenceConfig, etc)
    • Lifecycle control (ready, start, stop, setConfig, reset)
    • Location tracking (motion-based tracking, getCurrentPosition, watchPosition)
    • Geofencing (addGeofence, onGeofence, etc)
    • Events subsystem with fully-typed callbacks (onLocation, onMotionChange, onHttp, onProviderChange, etc)
    • Native services such as background-tasks, authorization workflows, scheduling, and device-capability checks
    • Persistence + HTTP via an internal SQLite buffer and optional auto-upload system

    Typed Configuration (Compound Config)

    Instead of a large “flat” configuration object, the SDK uses a compound-configuration model:

    import BackgroundGeolocation, {
    Config,
    GeoConfig,
    HttpConfig
    } from "react-native-background-geolocation";

    const config: Config = {
    geolocation: {
    desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High,
    distanceFilter: 20
    },
    http: {
    url: "https://example.com/locations",
    autoSync: true
    },
    persistence: {
    maxDaysToPersist: 7
    }
    };

    BackgroundGeolocation.ready(config);

    This structure ensures:

    • Clear separation of concerns
    • Type-safe configuration
    • Automatic backwards-compatibility with legacy flat keys

    Typed Enum Namespaces

    All configuration flags that were previously “magic constants”
    (e.g., LOG_LEVEL_VERBOSE, DESIRED_ACCURACY_HIGH) now live in
    strongly-typed namespaces attached to the default export:

    These can also be imported individually:

    import BackgroundGeolocation, { LogLevel } from "react-native-background-geolocation";

    BackgroundGeolocation.ready({
    logger: {
    logLevel: LogLevel.Debug
    }
    });

    Event System

    The SDK exposes a robust, typed event API:

    BackgroundGeolocation.onLocation((location) => {
    console.log("New location:", location);
    });

    BackgroundGeolocation.onMotionChange((event) => {
    console.log("Device is moving?", event.isMoving);
    });

    All events return Subscription objects which must be removed when no longer needed:

    const sub = BackgroundGeolocation.onHttp((e) => { ... });
    sub.remove();

    Native Lifecycle Requirements

    On both iOS and Android, BackgroundGeolocation.ready(config) must be called exactly once per app launch, before calling start().
    The SDK automatically restores its last-known configuration from persistent storage after first install.

    Philosophy of Operation

    Transistorsoft’s tracking engine is built around:

    • Motion-based state transitions (stationary ↔ moving)
    • Aggressive tracking only when moving
    • Energy-efficient passive monitoring when stationary
    • Reliable persistence via SQLite
    • Automatic retries + batching for HTTP uploads

    Combined, this enables battery-efficient, high-quality background tracking across iOS and Android.

    Capabilities

    • High-frequency tracking while the device is moving
    • Zero-movement battery preservation
    • Geofence monitoring at scale (thousands of geofences)
    • Offline storage + sync when network is restored
    • Background tasks for long-running operations
    • Authorization state + system diagnostics

    Getting Started

    import BackgroundGeolocation from "react-native-background-geolocation";

    const state = await BackgroundGeolocation.ready({
    geolocation: { distanceFilter: 10 },
    http: { url: "https://example.com/locations", autoSync: true }
    });

    if (!state.enabled) {
    await BackgroundGeolocation.start();
    }

    Once start() is called, the SDK begins operating according to your configuration and continues running—even in the background—until you call stop().

    interface BackgroundGeolocation {
        onLocation(
            cb: (location: Location) => void,
            onError?: (err: LocationError) => void,
        ): Subscription;
        onMotionChange(cb: (event: MotionChangeEvent) => void): Subscription;
        onGeofence(cb: (event: GeofenceEvent) => void): Subscription;
        onGeofencesChange(cb: (event: GeofencesChangeEvent) => void): Subscription;
        onActivityChange(cb: (event: MotionActivityEvent) => void): Subscription;
        onProviderChange(cb: (event: ProviderChangeEvent) => void): Subscription;
        onHeartbeat(cb: (event: HeartbeatEvent) => void): Subscription;
        onHttp(cb: (event: HttpEvent) => void): Subscription;
        onSchedule(cb: (state: State) => void): Subscription;
        onConnectivityChange(
            cb: (event: ConnectivityChangeEvent) => void,
        ): Subscription;
        onPowerSaveChange(cb: (enabled: boolean) => void): Subscription;
        onEnabledChange(cb: (enabled: boolean) => void): Subscription;
        onNotificationAction(cb: (buttonId: string) => void): Subscription;
        onAuthorization(cb: (event: AuthorizationEvent) => void): Subscription;
        removeListeners(): Promise<void>;
        registerHeadlessTask(
            callback: (event: HeadlessEvent) => Promise<void>,
        ): void;
        deviceSettings: DeviceSettings;
        logger: Logger;
        ready(config: Config): Promise<State>;
        reset(config: Config): Promise<State>;
        start(): Promise<State>;
        stop(): Promise<State>;
        changePace(isMoving: boolean): Promise<State>;
        startGeofences(): Promise<State>;
        getState(): Promise<State>;
        setConfig(config: Partial<Config>): Promise<State>;
        getCurrentPosition(options?: CurrentPositionRequest): Promise<Location>;
        watchPosition(
            cb: (location: Location) => void,
            options?: CurrentPositionRequest,
        ): Subscription;
        stopWatchPosition?(sub?: Subscription): void;
        resetOdometer(): Promise<number>;
        setOdometer(value: number): Promise<number>;
        getOdometer(): Promise<number>;
        getProviderState(): Promise<ProviderChangeEvent>;
        requestPermission(): Promise<AuthorizationStatus>;
        requestTemporaryFullAccuracy(
            purposeKey: string,
        ): Promise<AccuracyAuthorization>;
        addGeofence(geofence: Geofence): Promise<boolean>;
        addGeofences(geofences: Geofence[]): Promise<boolean>;
        removeGeofence(identifier: string): Promise<boolean>;
        removeGeofences(identifiers?: string[]): Promise<boolean>;
        getGeofences(): Promise<Geofence[]>;
        getGeofence(identifier: string): Promise<Geofence>;
        geofenceExists(identifier: string): Promise<boolean>;
        startSchedule(): Promise<void>;
        stopSchedule(): Promise<void>;
        setLogLevel(level: LogLevel): Promise<void>;
        setLogPersist(mode: PersistMode): Promise<void>;
        getDeviceInfo(): Promise<DeviceInfo>;
        getSensors(): Promise<Sensors>;
        isPowerSaveMode(): Promise<boolean>;
        destroyLocations(): Promise<void>;
        destroyLocation(uuid: string): Promise<void>;
        getLocations(): Promise<Object[]>;
        getCount(): Promise<number>;
        sync(): Promise<Object[]>;
        startBackgroundTask(): Promise<number>;
        stopBackgroundTask(taskId: number): Promise<void>;
        findOrCreateTransistorAuthorizationToken(
            orgname: string,
            username: string,
            url?: string,
        ): Promise<TransistorAuthorizationToken>;
        destroyTransistorAuthorizationToken(url: string): Promise<void>;
        LogLevel: { Off: 0; Error: 1; Warning: 2; Info: 3; Debug: 4; Verbose: 5 };
        DesiredAccuracy: {
            Navigation: -2;
            High: -1;
            Medium: 10;
            Low: 100;
            VeryLow: 1000;
            Lowest: 3000;
        };
        PersistMode: { All: 2; Location: 1; Geofence: -1; None: 0 };
        AuthorizationStrategy: { Jwt: "jwt"; Sas: "sas" };
        LocationFilterPolicy: { PassThrough: 0; Adjust: 1; Conservative: 2 };
        KalmanProfile: { Default: 0; Aggressive: 1; Conservative: 2 };
        HttpMethod: { Post: "POST"; Put: "PUT"; Patch: "PATCH" };
        TriggerActivity: {
            Walking: "walking";
            OnFoot: "on_foot";
            Running: "running";
            OnBicycle: "on_bicycle";
            InVehicle: "in_vehicle";
        };
        NotificationPriority: { Default: 0; High: 1; Low: -1; Max: 2; Min: -2 };
        Event: {
            Boot: "boot";
            Terminate: "terminate";
            Location: "location";
            MotionChange: "motionchange";
            ActivityChange: "activitychange";
            Geofence: "geofence";
            GeofencesChange: "geofenceschange";
            Http: "http";
            Heartbeat: "heartbeat";
            ProviderChange: "providerchange";
            Authorization: "authorization";
            ConnectivityChange: "connectivitychange";
            EnabledChange: "enabledchange";
            PowerSaveChange: "powersavechange";
            Schedule: "schedule";
            Notification: "notification";
        };
        LocationRequest: { Always: "Always"; WhenInUse: "WhenInUse"; Any: "Any" };
        AccuracyAuthorization: { Full: 0; Reduced: 1 };
        AuthorizationStatus: {
            NotDetermined: 0;
            Restricted: 1;
            Denied: 2;
            Always: 3;
            WhenInUse: 4;
        };
        ActivityType: {
            Other: 1;
            AutomotiveNavigation: 2;
            Fitness: 3;
            OtherNavigation: 4;
            Airborne: 5;
        };
    }
    Index

    Properties

    deviceSettings: DeviceSettings
    logger: Logger

    Logger API

    LogLevel: { Off: 0; Error: 1; Warning: 2; Info: 3; Debug: 4; Verbose: 5 }

    LogLevel Controls verbosity of the SDK logger.
    Used by LoggerConfig.logLevel.
    Values range from silent (Off) to extremely verbose (Verbose).

    BackgroundGeolocation.ready({
    logger: {
    logLevel: BackgroundGeolocation.LogLevel.Verbose
    }
    });
    DesiredAccuracy: {
        Navigation: -2;
        High: -1;
        Medium: 10;
        Low: 100;
        VeryLow: 1000;
        Lowest: 3000;
    }

    DesiredAccuracy Controls the native location engine’s target accuracy.
    Higher accuracy consumes more battery.
    Used by GeoConfig.desiredAccuracy.

    BackgroundGeolocation.ready({
    geolocation: {
    desiredAccuracy: BackgroundGeolocation.DesiredAccuracy.High
    }
    });
    PersistMode: { All: 2; Location: 1; Geofence: -1; None: 0 }

    PersistMode Controls which records the SDK persists to SQLite:
    locations only, geofences only, both, or none.
    Used by PersistenceConfig.persistMode.

    BackgroundGeolocation.ready({
    persistence: {
    persistMode: BackgroundGeolocation.PersistMode.All
    }
    });
    AuthorizationStrategy: { Jwt: "jwt"; Sas: "sas" }

    AuthorizationStrategy Defines how the HTTP service performs authorization.
    Includes basic, JWT, and custom strategies.
    Used by AuthorizationConfig.strategy.

    BackgroundGeolocation.ready({
    authorization: {
    strategy: BackgroundGeolocation.AuthorizationStrategy.Jwt
    }
    });
    LocationFilterPolicy: { PassThrough: 0; Adjust: 1; Conservative: 2 }

    LocationFilterPolicy Selects the filtering engine policy for noise-reduction and smoothing.
    Used by GeoConfig.locationFilter.

    Type Declaration

    • ReadonlyPassThrough: 0

      No filtering — accept all samples. Useful for debugging.

    • ReadonlyAdjust: 1

      Balanced (default) — applies moderate filtering to reject noisy samples.

      Dynamically adjusts acceptance thresholds for incoming samples, but never alters the raw latitude/longitude coordinates.

      When using LocationFilterPolicy.Adjust (the default), the SDK computes motion metrics such as:

      • distance deltas
      • implied speed
      • accuracy variance
      • heading stability

      It then applies adaptive gating rules to decide whether each sample should be:

      • accepted
      • ignored
      • rejected as noise

      Coordinates are never modified. This policy adjusts which samples are included, not how they are positioned.

      If LocationFilter.useKalman is enabled, additional smoothing may occur, but the physical coordinates of each accepted sample remain untouched.

    • ReadonlyConservative: 2

      Aggressive — filters heavily, preferring stability over responsiveness.

    BackgroundGeolocation.ready({
    geolocation: {
    filter: {
    policy: BackgroundGeolocation.LocationFilterPolicy.Adjust
    }
    });
    KalmanProfile: { Default: 0; Aggressive: 1; Conservative: 2 }

    KalmanProfile Selects a preset tuning profile for the Kalman filter used in the filtering engine (aggressive, moderate, or relaxed smoothing).

    Type Declaration

    • ReadonlyDefault: 0

      Balanced for general-purpose movement (default).

    • ReadonlyAggressive: 1

      Aggressive — responds faster to motion with less smoothing.

    • ReadonlyConservative: 2

      Conservative — maximum smoothing, slower reaction to change.

    BackgroundGeolocation.ready({
    geolocation: {
    kalmanProfile: BackgroundGeolocation.KalmanProfile.Aggressive
    }
    });
    HttpMethod: { Post: "POST"; Put: "PUT"; Patch: "PATCH" }

    HttpMethod Defines the HTTP method used for uploads (POST, PUT, etc).
    Used by HttpConfig.method.

    BackgroundGeolocation.ready({
    http: {
    method: BackgroundGeolocation.HttpMethod.Post
    }
    });
    TriggerActivity: {
        Walking: "walking";
        OnFoot: "on_foot";
        Running: "running";
        OnBicycle: "on_bicycle";
        InVehicle: "in_vehicle";
    }

    TriggerActivity Defines which physical motion activities can trigger motion-detection transitions (still → moving).
    Used by ActivityConfig.triggerActivities.

    BackgroundGeolocation.ready({
    activity: {
    triggerActivities: [
    BackgroundGeolocation.TriggerActivity.InVehicle
    ]
    }
    });
    NotificationPriority: { Default: 0; High: 1; Low: -1; Max: 2; Min: -2 }

    NotificationPriority
    Controls Android foreground-service notification priority and icon placement (top, bottom, hidden).
    Used by NotificationConfig.priority.

    Type Declaration

    • ReadonlyDefault: 0

      Default notification priority (normal weighting).

    • ReadonlyHigh: 1

      Notification strongly weighted to top of list; icon strongly weighted to the left.

    • ReadonlyLow: -1

      Notification weighted to bottom of list; icon weighted to the right.

    • ReadonlyMax: 2
    • ReadonlyMin: -2

      Notification strongly weighted to bottom of list; icon hidden.

    BackgroundGeolocation.ready({
    notification: {
    priority: BackgroundGeolocation.NotificationPriority.High
    }
    });
    Event: {
        Boot: "boot";
        Terminate: "terminate";
        Location: "location";
        MotionChange: "motionchange";
        ActivityChange: "activitychange";
        Geofence: "geofence";
        GeofencesChange: "geofenceschange";
        Http: "http";
        Heartbeat: "heartbeat";
        ProviderChange: "providerchange";
        Authorization: "authorization";
        ConnectivityChange: "connectivitychange";
        EnabledChange: "enabledchange";
        PowerSaveChange: "powersavechange";
        Schedule: "schedule";
        Notification: "notification";
    }

    Event Enumerates all event names emitted by the SDK (location, geofence, motionchange, heartbeat, etc).

    LocationRequest: { Always: "Always"; WhenInUse: "WhenInUse"; Any: "Any" }

    LocationRequest Defines the type of permission request made to iOS (Always, WhenInUse, or Any).
    Used by GeoConfig.locationAuthorizationRequest.

    BackgroundGeolocation.ready({
    geolocation: {
    locationAuthorizationRequest: BackgroundGeolocation.LocationRequest.Always
    }
    });
    AccuracyAuthorization: { Full: 0; Reduced: 1 }

    AccuracyAuthorization
    iOS 14+: Indicates whether the user granted full or reduced accuracy.
    Used by ProviderChangeEvent.accuracyAuthorization and requestTemporaryFullAccuracy.

    BackgroundGeolocation.onProviderChange((event) => {
    if (event.accuracyAuthorization ===
    BackgroundGeolocation.AccuracyAuthorization.Reduced) {
    // Handle reduced-accuracy case
    }
    });
    AuthorizationStatus: {
        NotDetermined: 0;
        Restricted: 1;
        Denied: 2;
        Always: 3;
        WhenInUse: 4;
    }

    AuthorizationStatus
    Represents OS-level authorization state for location-services
    (Denied, Restricted, Always, WhenInUse).
    Returned from requestPermission() and onProviderChange.

    const status = await BackgroundGeolocation.requestPermission();
    if (status === BackgroundGeolocation.AuthorizationStatus.Always) {
    // Good to start tracking
    }
    ActivityType: {
        Other: 1;
        AutomotiveNavigation: 2;
        Fitness: 3;
        OtherNavigation: 4;
        Airborne: 5;
    }

    ActivityType
    iOS-only: Specifies the type of user activity (AutomotiveNavigation, Fitness, OtherNavigation, etc).
    Used by GeoConfig.activityType.

    Type Declaration

    • ReadonlyOther: 1

      Default/unspecified activity.

    • ReadonlyAutomotiveNavigation: 2

      Automotive navigation activity.

    • ReadonlyFitness: 3

      Fitness (walking, running, etc).

    • ReadonlyOtherNavigation: 4

      Other navigation (non-automotive).

    • ReadonlyAirborne: 5

      Airborne activity (iOS 15+).

    Methods

    • [Android-only] Subscribe to button-clicks of a custom NotificationConfig.layout on the Android foreground-service notification.

      Parameters

      • cb: (buttonId: string) => void

      Returns Subscription

    • Removes all event-listeners.

      Calls [[Subscription.remove]] on all subscriptions.

      Returns Promise<void>

      BackgroundGeolocation.removeListeners();
      
    • Registers a Javascript callback to execute in the Android "Headless" state, where the app has been terminated configured with AppConfig.stopOnTerminate:false. The received eventobject contains aname(the event name) andparams` (the event data-object).

      ⚠️ Note Cordova & Capacitor

      ⚠️ Warning:

      • You must registerHeadlessTask in your application root file (eg: index.js).

      ⚠️ Warning:

      • Your function must be declared as async. You must await all work within your task. Your headless-task will automatically be terminated after executing the last line of your function.

      Parameters

      Returns void

      const BackgroundGeolocationHeadlessTask = async (event) => {
      const params = event.params;
      console.log("[BackgroundGeolocation HeadlessTask] -", event.name, params);

      switch (event.name) {
      case "terminate":
      // Use await for async tasks
      const location = await BackgroundGeolocation.getCurrentPosition({
      samples: 1,
      persist: false
      });
      console.log("[BackgroundGeolocation HeadlessTask] - getCurrentPosition:", location);
      break;
      }
      // You must await all work you do in your task.
      // Headless-tasks are automatically terminated after executing the last line of your function.
      await doWork();
      }

      BackgroundGeolocation.registerHeadlessTask(BackgroundGeolocationHeadlessTask);

      Debugging

      While implementing your headless-task It's crucial to observe your Android logs in a terminal via

      $ adb logcat *:S TSLocationManager:V ReactNativeJS:V

      TSLocationManager: [c.t.r.HeadlessTask onHeadlessEvent] 💀 event: connectivitychange
      TSLocationManager: [c.t.r.HeadlessTask createReactContextAndScheduleTask] initialize ReactContext
      TSLocationManager: [c.t.r.HeadlessTask onHeadlessEvent] 💀 event: providerchange
      TSLocationManager: [c.t.r.HeadlessTask onHeadlessEvent] 💀 event: terminate
      ReactNativeJS: '[BGGeoHeadlessTask] ', 'connectivitychange', taskId: 1
      TSLocationManager: [c.t.r.HeadlessTask invokeStartTask] taskId: 1
      TSLocationManager: [c.t.r.HeadlessTask invokeStartTask] taskId: 2
      TSLocationManager: [c.t.r.HeadlessTask invokeStartTask] taskId: 3
      ReactNativeJS: '[BGGeoHeadlessTask] ', 'providerchange', taskId: 2
      ReactNativeJS: '[BGGeoHeadlessTask] ', 'terminate', taskId: 3
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task start] startBackgroundTask: 1
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task start] startBackgroundTask: 2
      ReactNativeJS: *** [doWork] START
      ReactNativeJS: *** [doWork] START
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task start] startBackgroundTask: 3
      ReactNativeJS: *** [doWork] START
      .
      .
      .
      ReactNativeJS: *** [doWork] FINISH
      ReactNativeJS: *** [doWork] FINISH
      ReactNativeJS: *** [doWork] FINISH
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] stopBackgroundTask: 1
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] stopBackgroundTask: 2
      TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] stopBackgroundTask: 3
      TSLocationManager: [c.t.r.HeadlessTask$1 onHeadlessJsTaskFinish] taskId: 1
      TSLocationManager: [c.t.r.HeadlessTask$1 onHeadlessJsTaskFinish] taskId: 2
      TSLocationManager: [c.t.r.HeadlessTask$1 onHeadlessJsTaskFinish] taskId: 3

      ℹ️ See also:

    • Signal to the plugin that your app is launched and ready, proving the default Config.

      The supplied Config will be applied only at first install of your app — for every launch thereafter, the plugin will automatically load its last-known configuration from persistent storage. The plugin always remembers the configuration you apply to it.

      Parameters

      Returns Promise<State>

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

      ⚠️ Warning:

      • You must call .ready(confg) once and only once, each time your app is launched.
      • Do not hide the call to .ready(config) within a view which is loaded only by clicking a UI action. This is particularly important for iOS in the case where the OS relaunches your app in the background when the device is detected to be moving. If you don't ensure that .ready(config) is called in this case, tracking will not resume.

      The reset method.

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

      Config.reset: false

      Configuring the plugin with reset: false should generally be avoided unless you know exactly what it does. People often find this from the Demo app. If you do configure reset: false, you'll find that your Config provided to .ready is consumed only at first launch after install. Thereafter, the plugin will ignore any changes you've provided there. The only way to change the config then is to use setConfig.

      You will especially not want to use reset: false during development, while you're fine-tuning your Config options.

      The reason the Demo app uses reset: false is because it hosts an advanced "Settings" screen to tune the Config at runtime and we don't want those runtime changes to be overwritten by .ready(config) each time the app launches.

      ⚠️ If you don't undestand what reset: false does, NO NOT USE IT. If you blindly copy/pasted it from the Demo app, REMOVE IT from your Config.

      BackgroundGeolocation.reset();
      // Reset to documented default-values with overrides
      bgGeo.reset({
      distanceFilter: 10
      });
    • Resets the SDK configuration to documented default-values.

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

      Parameters

      Returns Promise<State>

    • Enable location + geofence tracking.

      This is the SDK's power ON button. The plugin will initially start into its stationary state, fetching an initial location before turning off location services. Android will be monitoring its Activity Recognition System while iOS will create a stationary geofence around the current location.

      ⚠️ Note: If you've configured a AppConfig.schedule, this method will override that schedule and engage tracking immediately.

      Returns Promise<State>

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

      ℹ️ See also:

    • Disable location and geofence monitoring. This is the SDK's power OFF button.

      Returns Promise<State>

      BackgroundGeolocation.stop();
      

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

      // Later when you want to stop the Scheduler (eg: user logout)
      BackgroundGeolocation.stopSchedule();
    • Manually toggles the SDK's motion state between stationary and moving.

      When provided a value of true, the plugin will engage location-services and begin aggressively tracking the device's location immediately, bypassing stationary monitoring.

      If you were making a "Jogging" application, this would be your [Start Workout] button to immediately begin location-tracking. Send false to turn off location-services and return the plugin to the stationary state.

      Parameters

      • isMoving: boolean

      Returns Promise<State>

      BackgroundGeolocation.changePace(true);  // <-- Location-services ON ("moving" state)
      BackgroundGeolocation.changePace(false); // <-- Location-services OFF ("stationary" 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.

      Returns Promise<State>

      // 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:

    • Return the current State of the plugin, including all Config parameters.

      Returns Promise<State>

      let state = await BackgroundGeolocation.getState();
      console.log("[state] ", state.enabled, state.trackingMode);
    • Re-configure the SDK's Config parameters. This is the method to use when you wish to change the plugin Config after ready has been executed.

      The supplied Config will be appended to the current configuration and applied in realtime.

      Parameters

      Returns Promise<State>

      BackgroundGeolocation.setConfig({
      desiredAccuracy: Config.DESIRED_ACCURACY_HIGH,
      distanceFilter: 100.0,
      stopOnTerminate: false,
      startOnBoot: true
      }).then((state) => {
      console.log("[setConfig] success: ", state);
      })
    • Retrieves the current Location.

      This method instructs the native code to fetch exactly one location using maximum power & accuracy. The native code will persist the fetched location to its SQLite database just as any other location in addition to POSTing to your configured [[Config.url]]. If an error occurs while fetching the location, catch will be provided with an [[LocationError]].

      See CurrentPositionRequest.

      See LocationError.

      Parameters

      Returns Promise<Location>

      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:

      • While getCurrentPosition will receive only one Location, the plugin does request multiple location samples which will all be provided to the onLocation event-listener. You can detect these samples via Location.sample == true.
    • Start a stream of continuous location-updates. The native code will persist the fetched location to its SQLite database just as any other location (If the SDK is currently [[State.enabled]]) in addition to POSTing to your configured [[Config.url]] (if you've enabled the HTTP features).

      ⚠️ Warning: watchPosition is not recommended for long term monitoring in the background — It's primarily designed for use in the foreground only. You might use it for fast-updates of the user's current position on the map, for example. The SDK's primary Philosophy of Operation does not require watchPosition.

      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.

      Parameters

      Returns Subscription

      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();
      }
    • Stop watch-position updates initiated from watchPosition.

      Parameters

      Returns void

      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:

    • Initialize the odometer to 0.

      Returns Promise<number>

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

      ⚠️ Note:

    • Initialize the odometer to any arbitrary value.

      Parameters

      • value: number

      Returns Promise<number>

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

      ⚠️ Note:

    • Retrieve the current distance-traveled ("odometer").

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

      Returns Promise<number>

      let odometer = await BackgroundGeolocation.getOdometer();
      

      ℹ️ See also:

      ⚠️ Warning:

      • Odometer calculations are dependent upon the accuracy of received locations. If location accuracy is poor, this will necessarily introduce error into odometer calculations.
    • Retrieves the current state of location-provider authorization.

      ℹ️ See also:

      • You can also listen for changes in location-authorization using the event onProviderChange.

      Returns Promise<ProviderChangeEvent>

      let providerState = await BackgroundGeolocation.getProviderState();
      console.log("- Provider state: ", providerState);
    • [iOS 14+] iOS 14 has introduced a new [Precise: On] switch on the location authorization dialog allowing users to disable high-accuracy location.

      The method requestTemporaryFullAccuracy (Apple docs) will allow you to present a dialog to the user requesting temporary full accuracy for the lifetime of this application run (until terminate).

      Configuration — Info.plist

      In order to use this method, you must configure your Info.plist with the Dictionary key: Privacy - Location Temporary Usage Description Dictionary

      The keys of this Dictionary (eg: Delivery) are supplied as the first argument to the method. The value will be printed on the dialog shown to the user, explaing the purpose of your request for full accuracy.

      If the dialog fails to be presented, an error will be thrown:

      • The Info.plist file doesn’t have an entry for the given purposeKey value.
      • The app is already authorized for full accuracy.
      • The app is in the background.

      Note: Android and older versions of iOS < 14 will return [[BackgroundGeolocation.ACCURACY_AUTHORIZATION_FULL]].

      Parameters

      • purposeKey: string

      Returns Promise<AccuracyAuthorization>

      BackgroundGeolocation.onProviderChange((event) => {
      if (event.accuracyAuthorization == BackgroundGeolocation.ACCURACY_AUTHORIZATION_REDUCED) {
      // Supply "Purpose" key from Info.plist as 1st argument.
      BackgroundGeolocation.requestTemporaryFullAccuracy("Delivery").then((accuracyAuthorization) => {
      if (accuracyAuthorization == BackgroundGeolocation.ACCURACY_AUTHORIZATION_FULL) {
      console.log('[requestTemporaryFullAccuracy] GRANTED: ', accuracyAuthorization);
      } else {
      console.log('[requestTemporaryFullAccuracy] DENIED: ', accuracyAuthorization);
      }
      }).catch((error) => {
      console.warn("[requestTemporaryFullAccuracy] FAILED TO SHOW DIALOG: ", error);
      });
      }
      });

      See also:

    • Adds a Geofence to be monitored by the native Geofencing API.

      Parameters

      Returns Promise<boolean>

      BackgroundGeolocation.addGeofence({
      identifier: "Home",
      radius: 150,
      latitude: 45.51921926,
      longitude: -73.61678581,
      notifyOnEntry: true,
      notifyOnExit: false,
      notifyOnDwell: true,
      loiteringDelay: 30000, // 30 seconds
      extras: { // Optional arbitrary meta-data
      zone_id: 1234
      }
      }).then((success) => {
      console.log("[addGeofence] success");
      }).catch((error) => {
      console.log("[addGeofence] FAILURE: ", error);
      });

      ℹ️ 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.
      • 📘 Geofencing Guide
    • Adds a list of Geofence to be monitored by the native Geofencing API.

      Parameters

      Returns Promise<boolean>

      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:

    • Removes a Geofence having the given Geofence.identifier.

      Parameters

      • identifier: string

      Returns Promise<boolean>

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

      ℹ️ See also:

    • Destroy all Geofence

      Parameters

      • Optionalidentifiers: string[]

      Returns Promise<boolean>

      BackgroundGeolocation.removeGeofences();
      

      ℹ️ See also:

    • Fetch a list of all Geofence in the SDK's database. If there are no geofences being monitored, you'll receive an empty Array.

      Returns Promise<Geofence[]>

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

      ℹ️ See also:

    • Fetch a single Geofence by identifier from the SDK's database.

      Parameters

      • identifier: string

      Returns Promise<Geofence>

      let geofence = await BackgroundGeolocation.getGeofence("HOME");
      console.log("[getGeofence] ", geofence);

      ℹ️ See also:

    • Determine if a particular geofence exists in the SDK's database.

      Parameters

      • identifier: string

      Returns Promise<boolean>

      let exists = await BackgroundGeolocation.geofenceExists("HOME");
      console.log("[geofenceExists] ", exists);

      ℹ️ See also:

    • Initiate the configured AppConfig.schedule.

      If a AppConfig.schedule was configured, this method will initiate that schedule. The plugin will automatically be started or stopped according to the configured AppConfig.schedule.

      To halt scheduled tracking, use stopSchedule.

      Returns Promise<void>

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

      ℹ️ See also:

    • Halt scheduled tracking.

      Returns Promise<void>

      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.

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

      ℹ️ See also:

    • Parameters

      Returns Promise<void>

    • Returns the device information.

      Returns Promise<DeviceInfo>

      const deviceInfo = await BackgroundGeolocation.getDeviceInfo();
      console.log(deviceInfo);
    • Returns the presence of device sensors accelerometer, gyroscope, magnetometer

      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.

      Returns Promise<Sensors>

      let sensors = await BackgroundGeolocation.sensors;
      console.log(sensors);
    • Fetches the state of the operating-system's "Power Saving" mode.

      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%).

      Returns Promise<boolean>

      let isPowerSaveMode = await BackgroundGeolocation.isPowerSaveMode;
      
    • Remove all records in SDK's SQLite database.

      Returns Promise<void>

      let success = await BackgroundGeolocation.destroyLocations();
      
    • Destroy a single location by Location.uuid

      Parameters

      • uuid: string

      Returns Promise<void>

      await BackgroundGeolocation.destroyLocation(location.uuid);
      
    • Retrieve a List of Location currently stored in the SDK's SQLite database.

      Returns Promise<Object[]>

      let locations = await BackgroundGeolocation.getLocations();
      
    • Retrieve the count of all locations current stored in the SDK's SQLite database.

      Returns Promise<number>

      let count = await BackgroundGeolocation.getCount();
      
    • Manually execute upload to configured HttpConfig.url of all Location records currently stored in the SDK's SQLite database.

      If the plugin is configured for HTTP with an HttpConfig.url and HttpConfig.autoSync false, the sync method will initiate POSTing the locations currently stored in the native SQLite database to your configured HttpConfig.url. When your HTTP server returns a response of 200 OK, that record(s) in the database will be DELETED.

      If you configured HttpConfig.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 HttpConfig.url), your callback will be executed after all the HTTP request(s) have completed. If the plugin failed to sync to your server (possibly because of no network connection), the failure callback will be called with an error message. If you are not using the HTTP features, sync will delete all records from its SQLite database.

      Returns Promise<Object[]>

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

      ℹ️ For more information, see the [[HttpEvent | HTTP Guide]]

    • Sends a signal to OS that you wish to perform a long-running task.

      The OS will keep your running in the background and not suspend it until you signal completion with the stopBackgroundTask method. Your callback will be provided with a single parameter taskId which you will send to the stopBackgroundTask method.

      Returns Promise<number>

      onLocation(location) {
      console.log("[location] ", location);

      // Perform some long-running task (eg: HTTP request)
      BackgroundGeolocation.startBackgroundTask().then((taskId) => {
      performLongRunningTask.then(() => {
      // When your long-running task is complete, signal completion of taskId.
      BackgroundGeolocation.stopBackgroundTask(taskId);
      }).catch(error) => {
      // Be sure to catch errors: never leave you background-task hanging.
      console.error(error);
      BackgroundGeolocation.stopBackgroundTask();
      });
      });
      }

      iOS: The iOS implementation uses beginBackgroundTaskWithExpirationHandler

      ⚠️ 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 stopBackgroundTask your taskId to prevent the OS from force-killing your application.

      Logging of iOS background tasks looks like this:

      ✅-[BackgroundTaskManager createBackgroundTask] 1
      .
      .
      .

      ✅-[BackgroundTaskManager stopBackgroundTask:]_block_invoke 1 OF (
      1
      )

      Android:

      The Android implementation launches a WorkManager task.

      ⚠️ The Android plugin imposes a limit of 3 minutes for your background-task before it automatically FORCE KILLs it.

      Logging for Android background-tasks looks like this (when you see an hourglass ⏳ icon, a foreground-service is active)

       I TSLocationManager: [c.t.l.u.BackgroundTaskManager onStartJob] ⏳ startBackgroundTask: 6
      .
      .
      .
      I TSLocationManager: [c.t.l.u.BackgroundTaskManager$Task stop] ⏳ stopBackgroundTask: 6
    • Signal completion of startBackgroundTask

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

      Parameters

      • taskId: number

      Returns Promise<void>

      BackgroundGeolocation.startBackgroundTask().then((taskId) => {
      // Perform some long-running task (eg: HTTP request)
      performLongRunningTask.then(() => {
      // When your long-running task is complete, signal completion of taskId.
      BackgroundGeolocation.stopBackgroundTask(taskId);
      });
      });
    • Find or create a Transistor authorization token.

      See TransistorAuthorizationService for more information.

      Parameters

      • orgname: string
      • username: string
      • Optionalurl: string

      Returns Promise<TransistorAuthorizationToken>

    • Destroy a Transistor authorization token.

      See TransistorAuthorizationService for more information.

      Parameters

      • url: string

      Returns Promise<void>

    Events

    • Subscribe to location events.

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

      Parameters

      Returns Subscription

      const subscription = 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.

      location

    • Subscribe to motionchange events.

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

      Parameters

      Returns Subscription

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

      ⚠️ Warning: autoSyncThreshold

      If you've configured [[Config.autoSyncThreshold]], it will be ignored during a onMotionChange event — all queued locations will be uploaded, since:

      • If an onMotionChange event fires into the moving state, the device may have been sitting dormant for a long period of time. The plugin is eager to upload this state-change to the server as soon as possible.
      • If an onMotionChange event fires into the stationary state, the device may be about to lie dormant for a long period of time. The plugin is eager to upload all queued locations to the server before going dormant.

      ℹ️ See also:

      motionchange

    • Subscribe to Geofence transition events.

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

      Parameters

      Returns Subscription

      const subscription = BackgroundGeolocation.onGeofence((event) => {
      console.log("[onGeofence] ", event);
      });

      __ℹ️ See also:

      geofence

    • 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 GeoConfig.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.

      Parameters

      Returns Subscription

      const subscription = BackgroundGeolocation.onGeofencesChange((event) => {
      let on = event.on; //<-- new geofences activated.
      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:

    • Subscribe to changes in motion activity.

      Your callback will be executed each time the activity-recognition system receives an event (still, on_foot, in_vehicle, on_bicycle, running).

      Android: Android MotionActivityEvent.confidence always reports 100%.

      Parameters

      Returns Subscription

      const subscription = BackgroundGeolocation.onActivityChange((event) => {
      console.log("[onActivityChange] ", event);
      });

      activitychange

    • 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".

      Parameters

      Returns Subscription

      const subscription = 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;
      }
      });

      ℹ️ See also:

      • You can explicitly request the current state of location-services using [[getProviderState]].

      ⚠️ 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.

      providerchange

    • Subscribe to periodic heartbeat events.

      Your callback will be executed for each AppConfig.heartbeatInterval while the device is in stationary state (iOS requires AppConfig.preventSuspend: true as well).

      Parameters

      Returns Subscription

      BackgroundGeolocation.ready({
      heartbeatInterval: 60,
      preventSuspend: true // <-- Required for iOS
      });

      const subscription = 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. heartbeat
    • Subscribe to HTTP responses from your server HttpConfig.url.

      Parameters

      Returns Subscription

      const subscription = BackgroundGeolocation.onHttp((response) => {
      let status = response.status;
      let success = response.success;
      let responseText = response.responseText;
      console.log("[onHttp] ", response);
      });

      ℹ️ See also:

      http

    • Subscribe to AppConfig.schedule events.

      Your callback will be executed each time a AppConfig.schedule event fires. Your callback will be provided with the current State: state.enabled will reflect the state according to your AppConfig.schedule.

      Parameters

      • cb: (state: State) => void

      Returns Subscription

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

      schedule

    • Subscribe to changes in network connectivity.

      Fired when the state of the device's network-connectivity changes (enabled -> disabled and vice-versa). By default, the plugin will automatically fire a connectivitychange event with the current state network-connectivity whenever the [[start]] method is executed.

      ℹ️ The SDK subscribes internally to connectivitychange events — if you've configured the SDK's HTTP Service (See [[HttpEvent | HTTP Guide]]) and your app has queued locations, the SDK will automatically initiate uploading to your configured {HttpConfig.url} when network connectivity is detected.

      Parameters

      Returns Subscription

      const subscription = BackgroundGeolocation.onConnectivityChange((event) => {
      console.log("[onConnectivityChange] ", event);
      });

      connectivitychange

    • Subscribe to state changes in OS power-saving system.

      Fired when the state of the operating-system's "Power Saving" mode changes. Your callback will be provided with a bool showing whether "Power Saving" is enabled or disabled. Power Saving mode can throttle certain services in the background, such as HTTP requests or GPS.

      ℹ️ 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%).

      Parameters

      • cb: (enabled: boolean) => void

      Returns Subscription

      const subscription = BackgroundGeolocation.onPowerSaveChange((isPowerSaveMode) => {
      console.log("[onPowerSaveChange: ", isPowerSaveMode);
      });

      powersavechange

    • Subscribe to changes in plugin [[State.enabled]].

      Fired when the SDK's State.enabled changes. For example, executing start and stop will cause the onEnabledChange event to fire.

      Parameters

      • cb: (enabled: boolean) => void

      Returns Subscription

      const subscription = BackgroundGeolocation.onEnabledChange(isEnabled => {
      console.log("[onEnabledChanged] isEnabled? ", isEnabled);
      });

      enabledchange