Skip to main content

flutter_get_background_loc 0.11.0 copy "flutter_get_background_loc: ^0.11.0" to clipboard
flutter_get_background_loc: ^0.11.0 copied to clipboard

Accurate background location for Flutter with GNSS quality metrics, fake-GPS detection, adaptive Kalman filtering and offline-safe uploads.

flutter_get_background_loc #

License: MIT

A Flutter plugin for accurate background location on Android and iOS, with no third-party dependencies.

  • Android foreground service (foregroundServiceType="location", stopWithTask=false, START_STICKY) with a permanent notification, a short per-dispatch wake lock (long lock is opt-in), automatic restart after the app is swiped away (onTaskRemoved + AlarmManager), a keep-alive alarm against hard process kills, optional start on boot, and a provider watchdog.
  • Single owner. Native code (Kotlin/Swift) is only the raw location source. Raw fixes are streamed to a headless background Dart isolate, the only owner of filtering (EKF) and the HTTP upload. There is no native uploader or filter, so nothing is posted twice.
  • Kinematic Adaptive EKF (pure Dart, portable, unit-tested): state [px, py, vx, vy] in a local ENU frame, adaptive R from position/speed/course accuracy, adaptive Q (innovation + Doppler acceleration), Mahalanobis gating of multipath jumps.
  • Quality gating that is the same on both platforms and null-safe (no satellites / HDOP null → evaluated on accuracy alone). Indoors the output degrades gracefully (good / degraded / coarse / held) instead of going silent.
  • GNSS quality (Android): satellites visible/used, C/N0, HDOP, full tracking (GnssMeasurementRequest.setFullTracking, Android 12+), Doppler uncertainty.
  • Mock-location detection without QUERY_ALL_PACKAGES: OS flags, an IMU-vs-GNSS check, teleport detection and Play Integrity tokens. Heuristics alone never accuse a user on one noisy cue.
  • Indoor detection, motion state machine (activity recognition + IMU), barometer floors, heartbeat, iOS relaunch after force-quit (significant changes + dynamic geofence).
  • A persistent upload queue (JSON lines) with exponential backoff + jitter, uuid + seq per record, 4xx bisecting, batching, Wi-Fi-only, still-gating.
  • Every feature is opt-in / opt-out through config and a disabled feature starts nothing (see Features & configuration).
┌──────────────────────────────────────────────────────────────────────────┐
│ UI isolate (your app)        FlutterGetBackgroundLoc                     │
│   positionStream, filterResultStream, sendResultStream, healthCheck,     │
│   sendLocation() ──relay──┐                       ▲ processed/sendResult │
├───────────────────────────┼───────────────────────┼──────────────────────┤
│ Native (Kotlin / Swift)   ▼                       │                      │
│   LocationService / LocationTracker ── RAW fix ──┐   EventBus (routing)  │
│   GnssMonitor, ImuMonitor, IntegrityHelper (Android)                     │
│   BackgroundEngine (headless FlutterEngine)      │                       │
├──────────────────────────────────────────────────┼───────────────────────┤
│ Background isolate (Dart) – the ONLY owner       ▼                       │
│   BackgroundRuntime → LocationPipeline                                    │
│     MockHeuristics → LocationFilterEngine (gating + Adaptive EKF)         │
│     → LocationUploader (PersistentQueue, retry) → HTTP POST               │
│     → publish('processed' / 'sendResult') to the UI                       │
└──────────────────────────────────────────────────────────────────────────┘

Channels: flutter_get_background_loc/methods (MethodChannel) and flutter_get_background_loc/events (EventChannel). Raw fixes are buffered natively (max 1000) until the background isolate calls backgroundReady.

Installation #

Not published on pub.dev yet. Use it as a git or path dependency:

dependencies:
  flutter_get_background_loc:
    git:
      url: https://github.com/abedputra/Flutter-Get-Background-Loc.git
    # or, for a local checkout:
    # path: ../flutter_get_background_loc

The background isolate runs the entry point flutterGetBackgroundLocBackgroundMain (already annotated with @pragma('vm:entry-point')). No extra Dart code is needed; just import the package.

Android #

All permissions, the service and the receivers are declared in the plugin manifest and merged automatically: ACCESS_FINE/COARSE/BACKGROUND_LOCATION, FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION, POST_NOTIFICATIONS, WAKE_LOCK, INTERNET, ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE, RECEIVE_BOOT_COMPLETED, REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, SCHEDULE_EXACT_ALARM (Android 12+, see Restart on Android 12+/14), ACTIVITY_RECOGNITION (runtime permission on Android 10+; ask with requestActivityRecognitionPermission(), without it still/moving detection uses the IMU only). The barometer is optional (uses-feature … barometer required=false). QUERY_ALL_PACKAGES is not used.

  • minSdk 24. Needs Google Play Services for the fused provider (falls back to raw GPS automatically) and for Play Integrity.
  • An http:// (non-https) endpoint needs android:usesCleartextTraffic="true" in your app.
  • Notification icon: put a monochrome drawable in your app (e.g. res/drawable/ic_stat_location.png) and set NotificationConfig(iconName: 'ic_stat_location'). Default: the launcher icon. See Customization for every notification, permission and text option.
  • Google Play: background location and REQUEST_IGNORE_BATTERY_OPTIMIZATIONS must be justified in Play Console (permission form + demo video), see the checklist.
  • The background engine registers only this plugin. Other plugins are not available in the background isolate (not needed: HTTP uses dart:io).

iOS #

Add to ios/Runner/Info.plist:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Location is used to track your trips.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location is used in the background so tracking keeps running.</string>
<key>NSMotionUsageDescription</key>
<string>Motion and barometer data detect still/moving and floors.</string>
<key>UIBackgroundModes</key>
<array>
  <string>location</string>
  <string>fetch</string>
</array>

NSMotionUsageDescription is required for activity recognition (CMMotionActivityManager) and the barometer (CMAltimeter); without it both are disabled automatically (no crash).

In AppDelegate.swift call restoreOnLaunch() so tracking and the background isolate come back when iOS relaunches the app in the background (significant change / geofence exit), including after a force-quit:

import Flutter
import UIKit
import flutter_get_background_loc

@main
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FlutterGetBackgroundLocPlugin.restoreOnLaunch()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

iOS 15.0 minimum. Geofence and relaunch need Always permission. Frameworks: CoreLocation, CoreMotion (the accelerometer needs no permission / Info.plist key).

Usage #

Quick start #

Call the permission flow from a widget (it needs a BuildContext) before startService. The flow shows in-app dialogs, then the system prompts: location → "Allow all the time" → notifications → activity recognition. If the permission was permanently denied, it offers to open the app settings. ensurePermissions() is a headless alternative (system prompts only, no in-app dialogs) and does not replace the flow.

import 'package:flutter_get_background_loc/flutter_get_background_loc.dart';

final bgLocation = FlutterGetBackgroundLoc();

// 1. Permissions (from a State / widget that has a BuildContext)
final perm = await LocationPermissionFlow.run(context, appName: 'My App');
if (!perm.completed) {
  // The user cancelled, or location is not "Allow all the time" yet.
  return;
}

// 2. Start the service (native + background Dart isolate)
await bgLocation.startService(
  config: LocationConfig(
    intervalMs: 1000,
    enableFullTracking: true,        // no GNSS duty cycling (Android 12+)
    accuracyThresholdMeters: 15.0,   // hAcc gate when HDOP is available
    notification: const NotificationConfig(
      title: 'Tracking active',
      text: 'Location is sent to the server',
    ),
    send: const SendConfig(
      url: 'https://api.example.com/v1/locations',
      headers: {'Authorization': 'Bearer <token>'},
      extraFields: {'driverId': 'D-01'},
      intervalMs: 10000,             // send every 10 s
      mode: SendMode.dart,           // default; handled by the background isolate
    ),
  ),
);

// 3. Listen to the cleaned position (processed by the background isolate)
bgLocation.positionStream.listen((fix) {
  print('Position: ${fix.latitude}, ${fix.longitude} ±${fix.accuracy} m');
  print('Speed: ${fix.speedKmh} km/h, quality ${fix.quality?.name}');
  print('Mock: OS flag ${fix.mockByOsFlag}, heuristic score ${fix.mockScore}, ${fix.mockReasons}');
  print('Indoor: ${fix.indoorLikely} (${fix.indoorReasons})');
  print('Satellites: ${fix.usedInFix}/${fix.satellites}, HDOP ${fix.hdop}, C/N0 ${fix.cn0}');
});

// Raw data and filter rejection reasons
bgLocation.rawLocationStream.listen((raw) {});
bgLocation.filterResultStream.listen((r) => print(r.decision)); // rejectedSpeedJump, ...

// 4. Send manually now: relayed to the background isolate (one upload path)
final result = await bgLocation.sendLocation(extraFields: {'event': 'checkpoint'});

// 5. Health check
final health = await bgLocation.healthCheck();
print(health.backgroundIsolateRunning);
print(health.warnings);

// 6. Stop
await bgLocation.stopService();

When the app is opened again while the service is still running, just listen to positionStream again; the UI reconnects and the background isolate keeps running.

Example payload #

{
  "latitude": 48.8583701, "longitude": 2.2944813,
  "accuracy": 3.8, "verticalAccuracy": 5.1, "altitude": 42.0,
  "speed": 8.33, "speedKmh": 30.0, "speedAccuracy": 0.4,
  "bearing": 91.5, "provider": "fused", "platform": "android",
  "isMock": false, "mockSuspected": false, "mockScore": 0.0, "mockReasons": [],
  "developerOptionsEnabled": false,
  "satellites": 31, "usedInFix": 19, "cn0": 33.2, "hdop": 0.8,
  "validMeasurements": 22, "measurementCn0": 34.0, "pseudorangeRateUncertainty": 0.12,
  "fullTracking": true, "imuRms": 0.84, "imuSamples": 20,
  "quality": "good", "ageMs": 0, "indoorLikely": false, "indoorScore": 0.0, "indoorReasons": [],
  "motionState": "moving", "activity": "walking", "stationary": false,
  "pressureHpa": 1009.8, "relativeAltitude": 0.0, "floorChange": 0, "floor": null,
  "verticalMotion": "none", "verticalSpeed": 0.0,
  "batteryLevel": 81, "isCharging": false, "wifiOn": true,
  "filtered": true, "rawLatitude": 48.8583732, "rawLongitude": 2.2944790, "rawAccuracy": 4.1,
  "timestamp": "2026-11-27T12:00:00.000Z", "timestampMs": 1795780800000,
  "uuid": "c6f6f49c-a54d-4bdd-8843-b9fafe795cae", "seq": 1,
  "driverId": "D-01"
}

batchSize > 1 sends a JSON array. A 2xx response = success; 4xx (except 408/429) = dropped; anything else / network errors = stays in the queue (flutter_get_background_loc_queue.jsonl in the app data directory) and is retried (retryBaseMs × 2ⁿ + jitter, max retryMaxMs). Which groups of fields are written is configurable (SendConfig.payload, see below).

Send modes #

Mode Description
SendMode.dart (default) The background Dart isolate filters and uploads. Works with the UI closed (Android: while the service lives; iOS: while tracking / after relaunch). Persistent queue.
SendMode.none No automatic upload; sendLocation() can still be used.

SendMode.native (0.1.x) was removed; the old value 'native' is read as dart.

Features & configuration #

Every feature can be switched on or off from LocationConfig; a disabled feature starts nothing (no sensor listener, no timer, no field in the output). Defaults are chosen to be safe for production; everything not marked "off" is on.

Feature Flag Default Platform Disabled means
Background tracking service startService / stopService – Android, iOS –
Automatic upload send (null = off), send.mode: SendMode.none off (send == null) both no uploader, no queue, no HTTP
Upload payload groups send.payload: PayloadConfig(speed, bearing, altitude, gnss, imu, mock, indoor, motion, barometer, device, quality, snap) all true both those keys are not in the JSON
Upload queue limits / retry send.maxQueueSize, retryBaseMs, retryMaxMs, timeoutMs 5000 / 5 s / 5 min / 15 s both –
Wi-Fi-only / no-cellular upload send.wifiOnly, send.disableOnCellular false both queue grows until allowed
Upload batching send.syncThreshold, send.maxSyncLatencyMs, send.batchSize 1 / 0 / 1 both one record per request
Still-gating of uploads send.stillOnlyIfMoved, stillMoveMeters, stillHeartbeatMs true / 25 m / 5 min both every fix is uploaded
Keep-alive HTTP client send.keepAlive true both one connection per request
Record ids (dedup/order) send.recordIds true both no uuid / seq
GNSS status (satellites, C/N0, HDOP, Doppler) enableGnssStatus true Android no GNSS listener; fields stay null, gating uses accuracy
Full GNSS tracking enableFullTracking true Android 12+ chipset may duty-cycle
IMU (accelerometer RMS) enableImu true both no sensor; IMU mock check and imuStill are inactive
Mock-location info mock.enabled (and mock.* thresholds) true both no OS-flag read, no heuristics, no mock* info
Indoor detection indoor.enabled true both no score/reasons, old strict gating
Indoor score + state (0.11.0) indoor.robust.enabled false both legacy indoorLikely only, no indoorState
Activity recognition motion.enableActivityRecognition true both not registered; IMU/speed drive the state machine
Low-power while still motion.balancedWhileStill, motion.stillIntervalMs, motion.stillMinDistanceMeters true / 30 s / 20 m both priority never changes
Low-power silence probe (0.11.0) motion.stillProbeIntervalMs (0 = off), motion.stillProbeDurationMs 120 s / 20 s Android low power ends only on motion evidence or the provider watchdog
Leave the parked anchor on an outward trail (0.11.0) indoor.anchorTrailExitEnabled (+ anchorTrailMinFixes, anchorTrailMinStepMeters, anchorTrailFarStepMeters, anchorTrailMaxAccuracyMeters) true (3 / 2 m / 50 m / 20 m) both the anchor is left only on IMU / activity / Doppler motion
Barometer / floors barometer.enabled true both no sensor, altitude/floor fields null
Wi-Fi radio state readWifiState true Android wifiOn never read (null)
Battery level readBattery true both never read (null)
Heartbeat heartbeat.enabled, heartbeat.upload true / false both no timer, no event
Short dispatch wake lock power.dispatchWakeLockMs (0 = off) 10 s Android no wake lock
Long wake lock useWakeLock false Android –
Location batching power.locationBatching true Android fixes delivered one by one
Restart after swipe restartOnTaskRemoved true Android service ends with the task
Keep-alive restart alarm restart.keepAliveMs (0 = off) 15 min Android no alarm armed
Alarm-clock style restart restart.useAlarmClock true Android setExactAndAllowWhileIdle instead
Resume notification restart.resumeNotification true Android restart failure is silent
Start on boot startOnBoot false Android –
Re-post dismissed notification notification.repostOnDismiss true Android –
Notification look & buttons notification.* (icons, colour, importance, templates, tap action, actions) built-in look Android built-in look; see Customization
iOS significant changes / geofence ios.useSignificantChanges, ios.useRegionMonitoring true iOS no relaunch after force-quit
iOS background activity session ios.useBackgroundActivitySession true iOS 17+ –
iOS activity type ios.activityType otherNavigation iOS –
Drive-mode detection drive.enabled (+ drive.useActivity, thresholds) true both no detector; driveMode stays false; nothing below applies
Vehicle EKF model (drive mode only) drive.vehicleModel true both drive mode is reported, the normal EKF model is used
iOS activity type while driving ios.driveActivityType (null = never switch) automotiveNavigation iOS ios.activityType is never changed
Drive elasticity (speed-proportional upload distance) filter.driveElasticity true both every fix is uploaded in drive mode
Road snapping a RoadSnapper via backgroundEntrypoint off (no snapper) both no map-matching code, no network, no snapped* keys
Snapped keys in the payload send.payload.snap true both snappedLatitude/Longitude/snapConfidence not uploaded
Play Integrity token requestIntegrityToken() (on demand) not called Android nothing runs
OEM autostart guide OemBackgroundHelper.ensureBackgroundPermission() (on demand) not called Android –
LocationConfig(
  // A minimal, battery-friendly configuration: no sensors besides the location source.
  enableImu: false,
  enableGnssStatus: false,
  readWifiState: false,
  readBattery: false,
  mock: MockConfig(enabled: false),
  indoor: IndoorConfig(enabled: false),
  motion: MotionConfig(enableActivityRecognition: false),
  barometer: BarometerConfig(enabled: false),
  heartbeat: HeartbeatConfig(enabled: false),
  restart: RestartConfig(keepAliveMs: 0),
  send: SendConfig(
    url: 'https://api.example.com/v1/locations',
    payload: PayloadConfig(gnss: false, imu: false, mock: false, indoor: false, barometer: false),
  ),
)

Switches that disable a sensor are listed in the first column group; PayloadConfig only shapes the uploaded JSON (the in-app streams still carry every field the platform produced). If you disable motion.enableActivityRecognition and do not need the permission, remove it from your app manifest (see Removing permissions you do not use).

Drive mode, road-hugging & road snapping #

Added in 0.6.0. All of it is optional and costs no sensor: drive mode only reads the filtered speed, the OS activity and the motion state that are already there.

LocationConfig(
  drive: DriveConfig(
    enabled: true,        // false = no detector at all (driveMode stays false)
    vehicleModel: true,   // false = report driveMode only, keep the normal EKF
    useActivity: true,    // false = decide on speed only
  ),
  filter: FilterConfig(driveElasticity: true),
  ios: IosConfig(driveActivityType: 'automotiveNavigation'), // null = never switch
)

Detection (hysteresis). driveMode turns on when the OS activity is vehicle, or the filtered speed stays above 15 km/h for 20 s; both also need the speed above 10 km/h. It turns off when the speed stays below 7 km/h for 60 s (a traffic light shorter than that never exits), when a walking/running activity lasts 30 s at walking speed, when a still activity lasts 60 s at standstill, or when the motion state becomes still. Fixes flagged as mock are ignored (no state change). driveMode is on every LocationFix, every payload (group motion), motionStream (MotionUpdate.driveMode, driveReason), Heartbeat.driveMode and healthCheck().driveMode. Every threshold is a DriveConfig field.

Vehicle EKF model (road-hugging), drive mode only. Process noise is anisotropic and rotated by the heading (lateral noise = 0.2 x longitudinal), a soft zero-lateral-velocity pseudo-measurement keeps the track on a straight road, and the course gets more trust above 5 m/s when its accuracy is below 15 degrees. The model steps aside by itself when it cannot know the heading (course accuracy >= 25 degrees) and during turns. The stationary anchor still handles stops; walking and standing behaviour is unchanged. Measured on the test scenario (straight road, +-8 m lateral noise, speed 7-17 m/s): lateral RMS error 2.6 m -> 1.3 m when the fix has no usable course; about -30 % with a poor (15 degree) course; neutral with a good course (the Doppler course already pins the direction). Do not expect magic on a good-course phone.

iOS. While drive mode is on CLLocationManager.activityType is switched to ios.driveActivityType and restored to ios.activityType on exit. Risk: automotiveNavigation lets iOS snap and pause updates to known roads; on unmapped roads (off-road, new estates, private roads, some countries) updates can become sparse or stop (see transistorsoft/flutter_background_geolocation#1027 and capacitor-background-geolocation#240). Set driveActivityType: null if your drivers use such roads.

Drive elasticity. In drive mode a fix is only uploaded after the vehicle moved speed x drive.elasticSeconds metres (clamped to elasticMinMeters..elasticMaxMeters, default 5..60 m), or after elasticMaxIntervalMs (10 s). It affects uploads (and the snapper input), not positionStream.

Road snapping (RoadSnapper). The package contains the interface only - no network code, no dependency:

abstract class RoadSnapper {
  /// One entry per input, same order, null = not matched. Throwing is allowed.
  Future<List<SnapPoint?>> snap(List<SnapInput> window);
}

It runs only in drive mode, on a sliding window of 5-10 fixes (drive.snapWindow), at most once per drive.snapIntervalMs (5 s), and gives up after drive.snapTimeoutMs (8 s): then the fixes are uploaded unsnapped, never dropped. Raw/filtered coordinates are kept; snappedLatitude, snappedLongitude and snapConfidence are added (payload group snap) and the fixes are also published on FlutterGetBackgroundLoc().snappedFixStream. Because objects cannot cross isolates, the snapper is created in the background isolate through your own entry point:

@pragma('vm:entry-point')
Future<void> myBackgroundMain() => runFlutterGetBackgroundLoc(roadSnapper: MySnapper());

LocationConfig(
  backgroundEntrypoint: BackgroundEntrypoint(
      library: 'package:my_app/main.dart', function: 'myBackgroundMain'),
)

example/lib/osrm_road_snapper.dart is an OsrmRoadSnapper (dart:io HttpClient, /match/v1/driving, configurable base URL). It defaults to the public demo server router.project-osrm.org, which is rate limited and not meant for production traffic - run your own OSRM instance for real use. The example and the field-test app have a "Road snapping" switch.

Filtering & gating #

Order per fix (in the background isolate):

  1. Mock heuristics → mockScore, mockReasons (optionally dropped with rejectMock: true).
  2. Quality gate (null-safe):
    • Geometry known = hdop != null and usedInFix ≥ minSatellitesForHdop (4): reject when HDOP

      maxHdop (rejectedHdop) or hAcc > accuracyThresholdMeters (rejectedAccuracy).

    • Geometry unknown (iOS, < 4 satellites, or HDOP null): accuracy only; reject when hAcc is missing or > fallbackAccuracyMeters (rejectedAccuracyNoHdop).
    • vAcc is not a hard gate by default (maxVerticalAccuracyMeters: null; indoor vAcc is often poor). vAcc > verticalConfidenceMeters (20 m) only lowers quality; set maxVerticalAccuracyMeters to reject (rejectedVerticalAccuracy).
    • hAcc between accuracyThresholdMeters (15) and indoor.coarseMaxAccuracyMeters (30, 50 before 0.9.0) is accepted as quality = coarse (see Indoor).
  3. Speed jump: reported speed > maxSpeedKmh (150) or implied speed between fixes (minus the accuracy margin) > 150 km/h → rejectedSpeedJump. After maxConsecutiveRejections in a row the reference point is reset (e.g. after a tunnel).
  4. Warm-up (stable accuracy) and spike (accuracy > spikeFactor × median).
  5. Kinematic Adaptive EKF:
    • State x = [px, py, vx, vy] in a local ENU plane (metres), constant-velocity model with random acceleration; the projection re-anchors automatically when it drifts away.
    • Position measurement R = hAcc²/2 per axis. Doppler velocity (Android speed/bearing + speedAccuracy/bearingAccuracy, with a floor from the GnssMeasurement pseudorange-rate uncertainty; iOS speed/course + accuracies) is converted to Cartesian with the polar→Cartesian Jacobian. Speed without course → non-linear measurement h(x) = |v|. Speed < 0.5 m/s → zero-velocity update.
    • Adaptive Q: accelStd follows the NIS (normalised innovation squared) and measured Doppler acceleration, clamped to minAccelStd..maxAccelStd.
    • Mahalanobis gating of the position (χ² 2-dof, default 13.8 ≈ 99.9 %) → rejectedJump (multipath). Re-initialisation after consecutive rejections or a gap > resetAfterGapMs.
    • Joseph-form update (covariance stays symmetric positive).
LocationConfig(
  accuracyThresholdMeters: 15,
  filter: FilterConfig(
    maxHdop: 4.0,
    minSatellitesForHdop: 4,
    fallbackAccuracyMeters: 15,      // used when HDOP is null / < 4 satellites
    maxVerticalAccuracyMeters: null, // null (default) = not a gate; set 20 for a hard gate
    maxSpeedKmh: 150,
    warmUpAccuracyMeters: 15,
    spikeFactor: 3.0,
    initialAccelStd: 1.5,            // m/s², adapted automatically
    minAccelStd: 0.3,
    maxAccelStd: 8.0,
    mahalanobisGate: 13.8,
    rejectMock: false,
  ),
)

FilterResult carries ekfAccelStd and ekfNis for diagnostics.

Mock-location detection #

No QUERY_ALL_PACKAGES, no third-party packages. Combined score mockScore = 1 − Π(1 − wᵢ):

Reason (mockReasons) Weight Source
isMock / isFromMockProvider / isSimulatedBySoftware 1.0 OS flag (hard evidence)
imuStationaryButMoved 0.6 Position moved > 10 m (and > accuracy) while the IMU says still. Suppressed (reason indoorDrift, score 0) when the jump is < driftAccuracyFactor (3) × accuracy, or the sky view is poor (indoorScore ≥ 0.3) and the jump is < indoorDriftMaxMeters
teleport 0.5 Implied speed > 300 km/h
native heuristic (e.g. a GPS fix with 0 satellites, accessory source) 0.4 native
developerOptions 0.05 hint only, never counts as a signal

mockSuspected is true only for an OS mock flag, or for heuristics when mockScore ≥ suspectThreshold (0.5) and at least minIndependentSignals (2) different heuristic layers fired. A single noisy cue (for example GNSS multipath wander next to a window while the phone lies still) never accuses an honest user, and developer options alone never flag anything. Use fix.mockByOsFlag (hard) and fix.mockByHeuristics (soft) to tell them apart in your UI.

IMU: Android TYPE_LINEAR_ACCELERATION (fallback: accelerometer + low-pass), iOS CMDeviceMotion.userAcceleration, 20 Hz, RMS per fix interval (imuRms, imuSamples).

LocationConfig(
  enableImu: true,
  mock: MockConfig(
    enabled: true,                 // false = no mock info at all
    imuStationaryRms: 0.15,        // m/s² – below this the phone counts as still
    minImuSamples: 5,
    minDisplacementMeters: 10,
    teleportSpeedKmh: 300,
    suspectThreshold: 0.5,
    minIndependentSignals: 2,
  ),
)

Play Integrity (Android) #

final token = await bgLocation.requestIntegrityToken(
  cloudProjectNumber: 123456789012,   // your Google Cloud project number
  requestHash: sha256OfRequest,       // optional, binds the token to a request
);
// Send the token to your server.

Uses the standard request of com.google.android.play:integrity (provider cached). Decode the verdict on your server (playintegrity.googleapis.com/v1/<package>:decodeIntegrityToken with a service account); never trust a decision made on the device. Check appIntegrity, deviceIntegrity (MEETS_DEVICE_INTEGRITY) and requestDetails.requestHash. On iOS the method throws PlatformException(code: 'unsupported') (use App Attest / DeviceCheck).

Indoor / high-rise #

Indoors a fused fix is typically 20–60 m. A strict 15 m gate would make the output go completely silent, reset the state after a 60 s gap, re-initialise the EKF onto a multipath cluster, and let IMU heuristics flag honest users. The indoor path avoids all of that:

# Feature Behaviour
1 Degraded output path hAcc ≤ 15 m → good; ≤ indoor.coarseMaxAccuracyMeters (30) → coarse (EKF R from hAcc, still filtered); worse / rejected by another gate → held: the last filtered fix is re-emitted with ageMs and accuracy acc + k·√age (holdAccuracyGrowth, max holdMaxAgeMs 10 min). A gap > 60 s does not reset warm-up / the EKF while the IMU says still. Upload policy: uploadCoarse (true), uploadHeld (false) + heldUploadIntervalMs.
2 Stationary anchor Still (IMU RMS + activity recognition) for ≥ anchorAfterStillMs (45 s) → the position is locked to the accuracy-weighted mean of the last anchorWindow good fixes, speed 0, small Q (stationary: true). Fast anchor (0.8.0): when the IMU window, the OS activity (still) and GNSS Doppler speed (< motion.gnssStillSpeedMps 0.5 m/s with a usable speedAccuracy) all agree, it engages after fastAnchorAfterStillMs (10 s); the 45 s path is the fallback. Anchor hold (0.8.0): while anchored a fix farther than max(anchorExitMinMeters, anchorExitAccuracyFactor × accuracy) (25 m / 2× acc) never reaches the EKF, however long it persists, and the position σ is capped at anchorMaxPositionStdMeters (2 m), so a persistent GNSS jump cannot win just because the covariance grew. Leaves only on IMU/activity motion and anchorExitConsecutive consecutive outside fixes, or (anchorSpeedExitEnabled) when Doppler speed says moving (≥ motion.gnssMovingSpeedMps 1.0 m/s for gnssSpeedMinFixes 3 fixes), so walking, cycling and driving are not sticky.
3 Safe EKF re-init After consecutive rejections, re-init only if the rejected fixes agree with each other (≤ reinitAgreementMeters), each has accuracy ≤ reinitMaxAccuracyMeters (15) and IMU/activity shows motion. Otherwise hold + inflate P (capped by reinitMaxInflation).
4 No false mock accusations Indoor drift is reported as indoorDrift, not imuStationaryButMoved (see the mock table).
5 indoorLikely + quality Score 0..1 (1−Π(1−w), threshold indoorLikelyThreshold 0.5). Cues: used satellites < 4 (0.35), mean C/N0 of used satellites < 28 dB-Hz (0.35, plus 0.30 below 20), ≥ 8 visible but < 40 % used (0.25), accuracy > 20 m (0.30) / > 40 m (0.50), non-GPS provider (0.25), IMU still (0.15), Wi-Fi radio off with poor accuracy (0.10). Low C/N0 plus many-visible-few-used is enough on its own. Present on every LocationFix and payload.
6 Activity recognition Android: Activity Recognition Transition API (play-services-location) via a manifest receiver + ACTIVITY_RECOGNITION; iOS: CMMotionActivityManager. A unknown/moving/still state machine with motion.stopTimeoutMs (default 3 min). Optional balancedWhileStill. A watchdog re-registers when silent (activityWatchdogMs).
7 Barometer Android TYPE_PRESSURE + SensorManager.getAltitude; iOS CMAltimeter. relativeAltitude, floorChange (≈ floorHeightMeters 3 m/floor), floor when calibrated (calibrateFloor(floor) in the lobby), verticalMotion (lift / stairs / none) + verticalSpeed. No sensor: fields stay empty, no error.

Measured on a real phone next to a high-floor window: 14–24 satellites used out of ~75 visible, mean C/N0 22–25 dB-Hz (open sky is typically 35–45), raw accuracy ~3 m but the position wandered up to ~12 m while the phone lay still. The current thresholds classify that as indoorLikely = true while open-sky data (C/N0 ≥ 35, ≥ 50 % of satellites used) stays false.

Driving away from a parked spot (0.11.0). A phone in a car holder can have a smooth IMU and no usable Doppler speed, so the motion exits of the stationary anchor may never fire. The anchor is also left on an outward trail: anchorTrailMinFixes (3) consecutive fixes outside the exit radius, each at least anchorTrailMinStepMeters (2 m) farther from the anchor than the previous one (or two fixes with an outward step of at least anchorTrailFarStepMeters, 50 m, for sparse low-power fixes), all with accuracy <= anchorTrailMaxAccuracyMeters (20 m). That counts as motion, so the low-power priority ends too. A static or back-and-forth multipath cluster or a slow drift never qualifies. When the EKF rejects a steady moving run of fixes (for example after a sharp turn without Doppler), it restarts on the newest fix with the run's speed and heading. While the anchored low-power priority is on, a fix outside the exit radius switches to high accuracy at once (probe), so the trail is confirmed with dense fixes; a blip that returns inside goes back to low power. Turn the trail logic off with anchorTrailExitEnabled: false.

Silence probe in low power (Android, 0.11.0). Some fused providers deliver no fix at all at balanced priority while the phone is driven away (a field drive had 17 minutes without a fix). Without fixes there is no motion evidence, so low power could only end on the 15-minute provider watchdog. When the balanced request has delivered nothing for MotionConfig.stillProbeIntervalMs (120 s), the service registers a high-accuracy request for stillProbeDurationMs (20 s). Those fixes go through the filter: a run away from the parked spot ends low power (outward trail above), otherwise the balanced request returns when the probe ends. A probe emits the status event stillProbe. Worst case while parked with no balanced fixes: 20 s of GNSS every 2 min. Set stillProbeIntervalMs: 0 to turn it off.

LocationConfig(
  motion: MotionConfig(
    stillProbeIntervalMs: 120000, // 0 = off
    stillProbeDurationMs: 20000,
  ),
)

Still / drift tuning (0.8.0). GNSS Doppler speed (with speedAccuracy) is a third still/motion input next to the IMU and the OS activity. It has hysteresis (still below 0.5 m/s, moving from 1.0 m/s, in between keeps the state) and needs 3 consecutive fixes; a fix without a speedAccuracy of at most 1 m/s is ignored. "Moving" is motion evidence (it ends the still window, so a smooth train or motorway car with a quiet IMU never anchors). "Still" never makes the state still on its own, it is only one vote of the fast anchor. A vehicle idling at a red light has activity vehicle, so it never takes the fast path; drive mode and the vehicle model are unchanged. Every part can be switched off:

LocationConfig(
  indoor: IndoorConfig(
    anchorHoldEnabled: true,            // false = 0.7.x (EKF gate only; a persistent jump can snap after ~1-2 min)
    anchorMaxPositionStdMeters: 2.0,    // 0 = no covariance cap while anchored
    anchorSpeedExitEnabled: true,       // Doppler "moving" releases the anchor at once
    fastAnchorEnabled: true,            // false = always wait anchorAfterStillMs
    fastAnchorAfterStillMs: 10000,
    fastAnchorMinFixes: 5,
    fastAnchorRequireActivity: true,    // false = IMU + GNSS speed decide (no activity permission needed)
  ),
  motion: MotionConfig(
    gnssSpeedEnabled: true,             // false = IMU + activity only
    gnssStillSpeedMps: 0.5, gnssMovingSpeedMps: 1.0,
    gnssSpeedMaxAccuracyMps: 1.0, gnssSpeedMinFixes: 3,
  ),
)

Diagnostics: LocationFilterEngine.anchorHeldCount (fixes dropped by the hold) and fastAnchorCount. test/replay/replay_field_log_test.dart replays a field log (JSON lines, one fix per line) offline through the filter.

Still / hand-jitter / low power (0.9.0). A phone in the hand rarely goes below IMU RMS 0.4, so the strict still thresholds kept the state at moving for hours. Now motion needs 2 consecutive fixes above imuMotionRms (or one strong shake), and while the OS activity AND the GNSS Doppler speed say still the relaxed hand-jitter thresholds apply (RMS <= 1.0 starts the still window, RMS > 1.5 for 5 consecutive fixes ends it). Fixes with hAcc above indoor.coarseMaxAccuracyMeters (now 30 m) never move the position. An anchor that froze on a drifting position moves to a persistent, agreeing cluster of contradicting fixes after 120 s, if the cluster is within 40 m of the anchor (anchorReanchor*; bigger jumps still need motion). While the anchor is held the receiver drops to balanced priority + stillIntervalMs and, on Android, the GNSS measurement listener is unregistered (it keeps the receiver tracking at 1 Hz); both return on motion. Opt-outs:

LocationConfig(
  indoor: IndoorConfig(
    coarseMaxAccuracyMeters: 50,        // 0.8.x reach (default 30)
    anchorReanchorEnabled: true,        // false = the anchor only ends by motion / Doppler speed
    anchorReanchorAfterMs: 120000, anchorReanchorMinFixes: 20, anchorReanchorMaxAccuracyMeters: 8, anchorReanchorMaxMeters: 40,
  ),
  motion: MotionConfig(
    imuMotionMinFixes: 2,               // 1 = every single fix above imuMotionRms is motion (0.8.x)
    imuStrongMotionRms: 2.0,
    handJitterEnabled: true,            // false = strict imuStillRms / imuMotionRms always
    imuJitterStillRms: 1.0, imuJitterMotionRms: 1.5, imuJitterMinFixes: 5,
    balancedWhenAnchored: true,         // false = low power only after stopTimeoutMs of stillness
    fullTrackingWhileStill: false,      // true = keep the GNSS measurement listener in low power
  ),
)

Diagnostics: LocationFilterEngine.reanchorCount.

LocationConfig(
  indoor: IndoorConfig(
    coarseMaxAccuracyMeters: 30,
    holdEnabled: true, holdMaxAgeMs: 600000, holdAccuracyGrowth: 2.0,
    uploadCoarse: true, uploadHeld: false, heldUploadIntervalMs: 30000,
    anchorAfterStillMs: 45000, anchorExitMinMeters: 25,
    indoorMinCn0: 28, indoorVeryLowCn0: 20, indoorUsedRatio: 0.4,
  ),
  motion: MotionConfig(stopTimeoutMs: 180000, balancedWhileStill: false),
  heartbeat: HeartbeatConfig(intervalMs: 60000, upload: false),
  barometer: BarometerConfig(floorHeightMeters: 3.0),
)

final loc = FlutterGetBackgroundLoc();
await loc.requestActivityRecognitionPermission();   // Android 10+ / iOS Motion & Fitness
loc.rejectedFixStream.listen((r) => print('${r.decision.name}: ${r.reason}, held=${r.held}'));
loc.heartbeatStream.listen((h) => print('${h.quality} age ${h.ageMs} ms'));
await loc.calibrateFloor(5);                        // "I am on floor 5" (e.g. in the lobby)

positionStream also emits held fixes (turn off with indoor.emitHeld: false). The legacy mode (indoor: IndoorConfig(enabled: false)) restores the 0.3.0 behaviour (unconditional EKF re-init).

Indoor score and state (opt-in, 0.11.0) #

The legacy indoorLikely flag above is a boolean built from many weak cues, and it can say "no" in a house even though the roof clearly weakens the signal, or "yes" next to a window. The optional detector gives a score from 0 (open sky) to 1 (obstructed) and a tri-state IndoorState (indoor / outdoor / unknown). It is off by default; nothing changes until you enable it:

LocationConfig(
  indoor: IndoorConfig(robust: RobustIndoorConfig(enabled: true)),
);
// later
final fix = loc.lastFilteredFix;            // fix.indoorState, fix.indoorScore, fix.indoorReasons
final health = await loc.healthCheck();     // health.indoorState, health.indoorScore

Android score = weighted mean of the cues that have data, each normalized to 0..1:

Cue 0 at 1 at Weight
Average horizontal accuracy over the last 15 s (accuracyWindowMs) 10 m 40 m 0.15
Mean C/N0 of the four strongest used satellites (LocationFix.cn0Top4) 35 dB-Hz 20 dB-Hz 0.10
Mean C/N0 of all used satellites (LocationFix.cn0) 32 dB-Hz 22 dB-Hz 0.65
Satellites used in the fix 8 0 0.10
  • A fix from the network provider raises the score to at least networkFloor (0.7).
  • Why the all-satellite mean carries most of the weight. With 30+ used satellites a phone indoors keeps a few strong ones (the top-4 mean stayed about 35 dB-Hz in a ground-floor house) and a 3 m accuracy from Wi-Fi/fused positioning, but the mean over all used satellites drops to about 25 dB-Hz because the roof and walls weaken most paths. The top-4 mean and the accuracy are kept as secondary cues (they catch deep indoor and poor fixes); set weightCn0Mean: 0 to disable the mean cue. Only fixes with at least one used satellite contribute to it.
  • A cue without data is skipped (weights renormalize). If less than minCoverage (0.6) of the weight has data, for example while GNSS measurements are paused because the phone lies still, the last score and state are held for staleHoldMs (2 min) and then become unknown. Accuracy alone is never enough on Android.
  • iOS exposes no satellite data: only the average accuracy counts, with separate thresholds (iosAccuracyOutdoorMeters 15 m -> 0, iosAccuracyIndoorMeters 65 m -> 1).
  • No Wi-Fi scanning, no light sensor, no magnetometer, no third-party package.

State with hysteresis (time windows, using the fix timestamps): indoor is entered when the score stays >= indoorEnterScore (0.7) for indoorEnterMs (12 s) and left when it stays < indoorExitScore (0.4) for indoorExitMs (4 s), then outdoor. In between the state is kept (indoor) or unknown. At least two fixes must support a change. indoorLikely is indoorState == indoor while enabled.

How the filter uses it - as a weight, never to drop data:

State Effect (all factors configurable)
indoor + still stationary anchor hold / exit radius x stillAnchorFactor (1.5): a stronger anchor
indoor + moving EKF measurement noise x movingNoiseFactor (2.0) and the slack of the implied-speed jump test x movingJumpMarginFactor (2.0)
outdoor / unknown unchanged

Typical values (one phone, the defaults): open sky (mean 34-37 dB-Hz, tight accuracy) scores below 0.15 and is outdoor; a ground-floor house (mean about 25, top-4 about 35, 32 satellites, 3 m) scores about 0.5 and stays unknown; deep indoor (mean about 20, few satellites, 35 m+) scores above 0.9 and becomes indoor after 12 s.

Honest limits. This measures sky obstruction, not "inside a building". A single-storey house with a light roof can legitimately look outdoor-ish, and a modern multi-constellation phone often keeps 25-40 used satellites and 3-5 m accuracy there; the score then lands in the undecided middle (unknown) instead of being forced to indoor. That is the honest reading of those signals. Tune cn0OutdoorDbHz, satellitesOutdoor and the thresholds with your own recordings (indoorScore, indoorState, cn0Top4 are part of every fix and the heartbeat). Low-end phones with fewer constellations give a different distribution than high-end ones.

Tracking presets #

One switch for the battery / accuracy trade-off. Pick a preset when you build the config, or change it while the service runs (no restart):

// at start
await FlutterGetBackgroundLoc().startService(
  config: LocationConfig.forPreset(TrackingPreset.powerSaver, base: myConfig),
);

// later, live: the fused request, the GNSS measurement listener and the sensors are re-applied in place
await FlutterGetBackgroundLoc().setPreset(TrackingPreset.highAccuracy);

// a preset plus individual overrides (or `TrackingPreset.custom` = only your values)
await FlutterGetBackgroundLoc().setPreset(TrackingPreset.balanced, intervalMs: 2000, distanceFilter: 3);

The active preset is reported in healthCheck() (HealthStatus.preset), in the presetChanged status event, in every heartbeat and in every fix (LocationFix.preset, payload group quality).

Preset Priority / rate GNSS measurements Still / anchored Expected accuracy Battery
powerSaver balanced power, 30 s / 25 m, batching off sparse (60 s / 50 m) ~20-50 m lowest
balanced (default) high, 1 s while moving on while moving, paused while still balanced priority, 30 s / 20 m ~3-15 m (10-30 m indoors) medium
highAccuracy high, 1 s, full tracking, no batching always on never drops to low power best the receiver can give highest
custom your values your values your values - -

The values are indicative. The development device is a mid-range Android phone; the accuracy ranges and the relative battery order come from the behaviour measured there with the balanced settings (see the still-drift notes above) and from the preset design, not from a full per-preset battery study (a per-preset drain run on the phone is still to be done). They depend on the device, the sky view, the network and the battery gauge; measure on your own hardware with the preset you plan to ship.

Screenshots: battery vs accuracy #

Per-preset runs from our internal test app on one Android test device: short sessions (about 5 minutes each), phone stationary and mostly indoors. Results vary a lot by device, sky view, network and battery gauge, so treat them as an illustration, not a benchmark.

Power saver Balanced High accuracy
Battery vs accuracy, power saver preset Battery vs accuracy, balanced preset Battery vs accuracy, high accuracy preset
Preset Session Mean current Drain Accuracy p50 / p95 (filtered) Fix rate
Power saver 6 min 266 mA 5.7 %/h no fix (indoors, network only) 0.00 /s
Balanced 5 min 277 mA ~6.5 %/h 1.4 / 16.0 m 0.17 /s
High accuracy 5 min 330 mA ~7.8 %/h 0.6 / 1.7 m 1.01 /s

~ = estimated from the mean current and the battery capacity (the preset ran for less than the 8 minutes needed for a measured drain). The current includes the screen, which was on during the runs.

Live accuracy example #

The same test app with the balanced preset, phone still: filtered accuracy 1.7 m (raw 3.0 m), 39 of 76 visible satellites used, mean C/N0 23.6 dB-Hz, HDOP 0.5, quality good (classified as open sky), no mock-location signal.

Live accuracy example: filtered 1.7 m, raw 3.0 m, 39/76 satellites, HDOP 0.5

GNSS warm-up (offline readiness) #

Optional and off by default. Nothing changes for existing apps unless you call warmUpGnss or set LocationConfig.warmUp.autoWarmUpBeforeStart.

A GPS receiver needs assistance data for a fast start: the broadcast ephemeris is only valid for about 2-4 hours, and Android additionally downloads predicted orbits (XTRA / PSDS, valid for about a week) while the device is online. After a long time without a fix, or without ever having been online, a cold start can take minutes, which hurts in a forest, on a hiking trail or right after a flight. warmUpGnss lets you prime the receiver before the device goes offline:

final loc = FlutterGetBackgroundLoc();
await loc.ensurePermissions();            // the warm-up never shows a permission dialog itself

final r = await loc.warmUpGnss(
  timeout: const Duration(seconds: 90),   // give up after this long (default 60 s)
  targetAccuracyM: 20,                    // success once a fix is at least this accurate (default 25 m)
  requireNetwork: true,                   // fail when offline (default false)
);

if (r.success) {
  print('TTFF ${r.timeToFirstFix}, ${r.accuracyMeters} m, '
      '${r.satellitesUsed}/${r.satellitesVisible} satellites, network: ${r.networkAvailable}');
} else {
  // permissionDenied, preciseLocationRequired, locationDisabled, networkUnavailable,
  // unsupported, timeout, accuracyNotReached, alreadyRunning, error
  print('Warm-up failed: ${r.reason} ${r.message}');
}

warmUpGnss returns a GnssWarmUpResult and never throws:

Field Meaning
success / reason / message Reached the accuracy target, or why not (GnssWarmUpFailure)
timeToFirstFix Android: the OS value (GnssStatus.Callback.onFirstFix) when available, else measured locally
accuracyMeters Best horizontal accuracy seen (also reported when the target was missed)
satellitesVisible / satellitesUsed Largest counts seen during the session (Android; can be null for very short sessions)
networkAvailable A validated internet connection existed at the start (null = unknown)
assistance What happened to the best-effort assistance refresh (attempted, accepted, rejected, skippedReason)
fixesReceived, trackingWasRunning, elapsed, provider, completedAt Session details

It does not need the tracking service and does not interfere with it. The warm-up uses its own short listener (Android: LocationManager.GPS_PROVIDER + GnssStatus callback; iOS: its own CLLocationManager). If tracking runs, the fixes keep flowing as before and trackingWasRunning is true. Only one warm-up runs at a time (alreadyRunning).

Stale GNSS data in HealthStatus #

HealthStatus.lastGnssFixAt is the time of the last real GNSS fix (Android: a gps-provider fix, or a fused fix while the receiver reported satellites used; persisted across restarts and also updated by warmUpGnss). gnssDataAge is the time since then and isGnssDataStale([threshold = 4 h]) is a ready made check, so you can warn users before they go offline:

final h = await loc.healthCheck();
if (h.isGnssDataStale()) {
  // "GPS data may be stale: open the app outdoors for a minute before you lose coverage."
}

On iOS CoreLocation does not expose the source of a fix, so the value is the time of the last fix with a horizontal accuracy of 50 m or better. The stale-data check is not part of warnings; it is yours to use.

Optional automatic warm-up #

await loc.startService(
  config: LocationConfig(
    warmUp: GnssWarmUpConfig(
      autoWarmUpBeforeStart: true,        // default false
      timeout: Duration(seconds: 45),
      targetAccuracyM: 25,
      requireNetwork: false,
    ),
  ),
);

With autoWarmUpBeforeStart startService first runs a warm-up (so startService takes up to timeout longer), publishes the outcome on statusStream (status: gnssWarmUp, with the result map in result) and starts tracking whatever the outcome. Automatic restarts (boot, swipe-away) never warm up; only a startService call from the UI does.

Assistance data refresh (Android, best effort) #

When refreshAssistance is true (default), the warm-up first asks the OS to refresh assistance data with LocationManager.sendExtraCommand("gps", ...) and the commands force_time_injection, force_psds_injection and the legacy force_xtra_injection. Each call is wrapped in try/catch; the result lists which ones the OS accepted. It needs the normal permission below in your app manifest (the plugin does not declare it, so apps that never use the feature do not get it):

<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />

Without it assistance.skippedReason is permissionMissing; offline it is networkUnavailable. The plugin never sends delete_aiding_data.

Honest caveats #

  • Best effort and OS dependent. Whether the OS downloads or applies anything is up to the vendor GNSS stack. accepted means the call returned true, not that fresh data arrived. Many devices ignore some or all of the commands (the time-to-first-fix value is the only real evidence).
  • Nothing can guarantee that assistance data is downloaded. Even with a network connection the provider (Google's XTRA / SUPL servers, the chipset vendor) decides. Some devices use data that was downloaded long ago, some need a data connection rather than Wi-Fi.
  • Ephemeris still expires after about 2-4 hours. A warm-up before going offline helps for the next few hours; after a day offline a cold start is slow again. Predicted orbits (about a week) only help if the OS downloaded them.
  • The receiver has to see the sky: indoors the warm-up typically ends with timeout or accuracyNotReached. Keep the device outdoors for a meaningful result.
  • A warm-up uses the GPS for up to timeout: it costs battery, and needs precise location (preciseLocationRequired when only approximate location is granted).
  • iOS manages assistance data itself and has no API to refresh it. The iOS warm-up only runs a short kCLLocationAccuracyBest session until the accuracy target or the timeout, and assistance.skippedReason is managedByOs.

Power, batching & restart #

Findings from studying geolocator, location, background_locator_2, flutter_foreground_task, flutter_background_service and Transistorsoft.

Wake lock #

LocationConfig.useWakeLock is off by default. The service normally takes a short wake lock acquire(PowerConfig.dispatchWakeLockMs = 10000) each time a batch of fixes is forwarded to the background isolate. The long lock is opt-in (useWakeLock: true, raw GPS mode) and always has a timeout (PowerConfig.wakeLockTimeoutMs, default 10 min; the 60 s watchdog re-acquires it).

Restart on Android 12+/14 #

  • The manifest declares SCHEDULE_EXACT_ALARM (special permission granted by the user in Alarms & reminders; denied by default on Android 13+). USE_EXACT_ALARM is deliberately not declared: Google Play restricts it to alarm/calendar apps. Explain the use of SCHEDULE_EXACT_ALARM (restarting tracking after the system stopped it) in Play Console.
  • API: canScheduleExactAlarms() and openExactAlarmSettings().
  • When allowed, restart uses AlarmManager.setAlarmClock (Doze-exempt, may start an FGS from the receiver; Android shows an alarm icon; disable with RestartConfig(useAlarmClock: false) → setExactAndAllowWhileIdle). Without the permission: setAndAllowWhileIdle.
  • Before scheduling, ACCESS_BACKGROUND_LOCATION and (exact alarms allowed or battery optimisation ignored) are checked. When blocked (or refused by the OS: ForegroundServiceStartNotAllowedException, SecurityException): status restartBlocked plus a "Tap to resume tracking" notification (RestartConfig.resumeTitle/resumeText) that restarts the service when tapped (a notification tap is a user interaction, so starting an FGS is allowed). healthCheck() includes restartBlocked and canScheduleExactAlarms.
  • Keep-alive alarm (0.5.3). On real HyperOS hardware a hard kill (SIGKILL, am crash, an OEM task killer) was not recovered by START_STICKY. While tracking, RestartConfig.keepAliveMs (default 15 min, 0 = off) keeps one setExactAndAllowWhileIdle alarm armed that the running service keeps sliding forward; it only fires after the process died. Cancelled by stopService().

Location batching (Android) #

PowerConfig.locationBatching → setMaxUpdateDelayMillis(interval × maxUpdateDelayFactor) (factor 10–60, capped by maxUpdateDelayCapMs) while STILL or when send.intervalMs ≥ 30 s. A batch is sorted by timestamp natively; in Dart, fixes older than the last EKF update are dropped (FilterDecision.rejectedStale). flushLocations() is called automatically on stop, on priority / motion-state changes and when the UI opens (it is also public API). IMU/barometer data is attached only to the newest fix of a batch.

Upload batching #

SendConfig(
  url: '...',
  syncThreshold: 10,        // wait for >= 10 fixes; one request = JSON array (max(batchSize, syncThreshold))
  maxSyncLatencyMs: 120000, // but also send when the oldest fix is this old
  wifiOnly: true,           // Wi-Fi/ethernet only (queue keeps growing on cellular)
  disableOnCellular: false, // or: never on a cellular network
  stillOnlyIfMoved: true,   // while STILL: enqueue only when moved > stillMoveMeters (25 m)
  stillHeartbeatMs: 300000, //   or when the "heartbeat" is due
  keepAlive: true,          // one HttpClient is reused (HTTP keep-alive)
)

The queue is flushed immediately on a motion-state change, on a manual sendLocation() and via flushQueue(). wifiOnly / disableOnCellular use ConnectivityManager (Android) and NWPathMonitor (iOS); a blocked manual send returns a SendResult with the reason.

Uploads are sent with an explicit Content-Length (no chunked encoding): many servers and proxies read a chunked body as empty (found on a real device in 0.5.2).

Low power while still #

While STILL (MotionConfig, default balancedWhileStill: true): Android balanced priority, interval stillIntervalMs (30 s), setMinUpdateDistanceMeters(stillMinDistanceMeters = 20) + batching; iOS desiredAccuracy = stillIosAccuracy (hundredMeters) and distanceFilter = stillMinDistanceMeters. Updates are never stopped, only made sparse (so no fixes arrive while the phone is parked). Moving: back to high accuracy at intervalMs (1 s). The watchdog does not restart the provider merely because it is silent in this mode.

Location switched off & notification swiped away (Android) #

  • PROVIDERS_CHANGED_ACTION / MODE_CHANGED_ACTION: status locationDisabled / locationEnabled, the watchdog stops restarting while GPS is off, the notification text changes ("Location is off - turn on GPS so tracking can continue") and the provider is re-registered when GPS comes back.
  • Android 14 allows FGS notifications to be swiped away: deleteIntent re-posts the notification (NotificationConfig.repostOnDismiss, default true) and emits status notificationDismissed.

Background isolate #

The entry point does not call DartPluginRegistrant.ensureInitialized() (since 0.5.1): the isolate is the root isolate of a headless FlutterEngine, and Flutter's docs forbid that call there (release crashes, e.g. flutter_background_service #375/#428). Plugins still register through the engine: on Android the FlutterEngine(context) constructor registers the app's plugins; on iOS BackgroundEngine registers this plugin (other plugins: setPluginRegistrantCallback).

iOS: background task & BGAppRefreshTask #

Every queue flush is wrapped in beginBackgroundTask / endBackgroundTask natively. Optional BGAppRefreshTask that retries the queue:

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array><string>com.example.app.refresh</string></array>
<!-- UIBackgroundModes already contains: location, fetch -->
// AppDelegate.didFinishLaunchingWithOptions, BEFORE return
FlutterGetBackgroundLocPlugin.registerBackgroundRefresh(identifier: "com.example.app.refresh")

iOS decides the timing (usually ≥ 15 minutes, not guaranteed).

iOS reduced accuracy #

requestTemporaryFullAccuracy('Navigation') (the key must exist in NSLocationTemporaryUsageDescriptionDictionary) returns full / reduced. Fixes with approximate location carry reducedAccuracy: true and are always coarse regardless of hAcc.

First fix (Android) #

setMaxUpdateAgeMillis(0) (no cached location for the EKF) and setWaitForAccurateLocation(true) on start; the wait is capped at 30 s / the first fix, then the request is re-registered without waiting.

MSL altitude & iOS 17 #

Android 14+: altitudeMsl / altitudeMslAccuracy (Location.getMslAltitudeMeters) on fixes and payloads. iOS 17+: IosConfig.useBackgroundActivitySession (default true) holds a CLBackgroundActivitySession for While Using users (created only when started in the foreground).

Robust upload queue, Play Store & server #

Corruption-proof queue #

  • On load, every line of the queue file (flutter_get_background_loc_queue.jsonl) is jsonDecoded and must be a JSON object. Corrupt / torn lines (process died mid-write, disk full) are discarded and counted: status queueCorrupt + LocationUploader.corruptLines; the file is rewritten clean (temp file + atomic rename), and a missing trailing newline is repaired so the next append does not glue onto a torn line.
  • Writes: appends are flushed, rewrites are atomic.
  • 4xx bisect. When the server answers 4xx (except 408/429) for a batch, the batch is split in two and each half retried (recursively) so only the bad record(s) are dropped; the rest is delivered. SendResult.sentCount / droppedCount report the outcome. A transient failure (5xx, timeout) while splitting stops the process and leaves the undelivered records in the queue.

uuid + seq on every payload (server-side dedup & ordering) #

SendConfig.recordIds (default true) adds to every record:

Field Content
uuid Random UUID v4 (Random.secure, no package), created once when the record enters the queue
seq A persisted, monotonically increasing integer (<queue>.seq; saved in blocks of 100 so it never goes backwards after a crash, gaps are allowed)

Retries, re-sent batches after a timeout and restarts carry the same uuid/seq. Your server should:

  1. Dedup: a unique index on uuid (INSERT … ON CONFLICT (uuid) DO NOTHING) and answer 2xx for duplicates.
  2. Order: store seq (and timestampMs) and ORDER BY seq – OS batching / Wi-Fi-only makes requests arrive late or out of order. seq only grows per installation (it restarts from 1 if the app data is cleared); combine it with a device id / driverId.
  3. Answer 4xx only for records that are really invalid (they will be dropped); 5xx/429 are retried.

Android start pre-check #

startService() first checks the location permission (Android 14 throws SecurityException for an FGS of type location without it) and, when the app is in the background, the same rules as a restart (ACCESS_BACKGROUND_LOCATION and exact alarm / battery exemption). If not allowed, startService returns false, with an error event startBlocked + status startBlocked carrying the reason (also healthCheck().startBlocked); ForegroundServiceStartNotAllowedException / SecurityException from the OS are caught → startForegroundFailed. In the service startForeground() is called first in onStartCommand (a minimal fallback notification if the full one cannot be built), the config is read from a cache (ConfigStore memoised and pre-warmed on a background thread), and every later failure is reported (startFailed).

Exact-alarm permission changes #

A receiver for ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED: when the permission is granted → status exactAlarmGranted, restartBlocked is cleared and the restart is rescheduled (or the service is started right away if it should be running); when revoked → status exactAlarmRevoked.

Wi-Fi & indoor accuracy (Android) #

Fused location uses access-point scanning: the Wi-Fi radio must be on, not connected (or "Wi-Fi scanning" enabled in Location settings). healthCheck() has wifiEnabled and wifiScanAvailable (+ a "Wi-Fi is off" warning); each fix carries wifiOn, and the indoor score adds the reason wifiOff (weight 0.10, only when accuracy is already poor). The manifest adds ACCESS_WIFI_STATE (a normal permission; it neither scans nor reads the SSID). Disable with readWifiState: false.

Background-location disclosure (Google Play) #

final out = await BackgroundLocationDisclosure.requestWithDisclosure(
  context,
  appName: 'Fast Courier',
  texts: const BackgroundDisclosureTexts(
    purpose: 'track the courier position while delivering parcels',
    footer: 'Privacy policy: https://example.com/privacy',
  ),
);
if (!out.accepted) return; // no system prompt is shown
// out.permission == LocationPermissionStatus.always -> continue with startService

The default dialog is in English, cannot be dismissed by tapping outside (an explicit choice is required), appears before the system location / background prompt, and is skipped when the permission is already always. Replace the text with BackgroundDisclosureTexts ({app} and {purpose} are substituted) or your own UI through builder. Keep the three mandatory statements: the app collects location data, even when the app is closed or not in use, and which feature uses it.

Google Play checklist

(Location permissions & User Data policies)

  1. Play Console → App content → Sensitive app permissions → Location: fill in the Background location access declaration; explain the core feature that needs background location and why foreground location is not enough.
  2. Demo video (YouTube, unlisted, ≤ 30 s): show the user enabling the feature, the disclosure dialog (above), the system prompt "Allow all the time" and the feature running in the background (the tracking notification).
  3. Privacy policy: a public URL in Play Console and in the app; state which location is collected, the purpose, where it is sent (your server), retention and how to delete the data.
  4. Data safety form: Location (approximate & precise) collected + shared if sent to a server; mark the purpose (App functionality) and encryption in transit (use HTTPS).
  5. Justify SCHEDULE_EXACT_ALARM (restart) and REQUEST_IGNORE_BATTERY_OPTIMIZATIONS if asked; do not use USE_EXACT_ALARM.
  6. Do not ask for background permission the first time the app opens without context; call requestWithDisclosure when the user turns the tracking feature on.

Removing permissions you do not use #

The plugin declares ACTIVITY_RECOGNITION (Activity Transition API, still/moving detection). If you disable motion.enableActivityRecognition and do not need the permission (avoiding Play questions / a prompt), remove it in your app manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools">
  <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" tools:node="remove" />
  <!-- without Wi-Fi state: -->
  <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" tools:node="remove" />
</manifest>

Without that permission the plugin still works (still/moving detection uses the IMU / speed). Without ACCESS_WIFI_STATE, wifiEnabled / wifiOn are null.

iOS: didFailWithError #

kCLErrorDomain 1 (denied) → status and error permissionDenied; code 0 (locationUnknown, transient) → status locationUnknown only; other errors → locationError with domain/code.

iOS: surviving a force-quit #

  • Normal tracking: startUpdatingLocation, allowsBackgroundLocationUpdates, pausesLocationUpdatesAutomatically = false.
  • Significant location change (useSignificantChanges, ~500 m) and a dynamic geofence (useRegionMonitoring, radius geofenceRadiusMeters default 200 m, minimum 100 m) around the last accurate fix; re-armed when the user moves > ½ radius and on every didExitRegion.
  • Both relaunch an app that was force-quit. restoreOnLaunch() in the AppDelegate restarts the standard updates + the background Dart isolate; the statuses restored / geofenceExit go to statusStream.

Devices with a "battery killer" (Xiaomi, Oppo, Vivo, Samsung, …) #

A foreground service + stopWithTask=false + START_STICKY is often not enough on MIUI/HyperOS, ColorOS, FuntouchOS, One UI, etc. The plugin ships helpers built from scratch (no disable_battery_optimization_2 / flutter_doki) over the plugin's own MethodChannel:

Native (Kotlin) Dart
PowerManager.isIgnoringBatteryOptimizations isBatteryOptimizationIgnored()
ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS (package: URI, NEW_TASK) requestDisableBatteryOptimization()
Build.MANUFACTURER getManufacturer()
per-vendor autostart activity candidates openOemAutostartSettings() → OemSettingsResult
non-stock vendor families needsOemAutostart()
SharedPreferences ("user confirmed" flag) used internally by OemBackgroundHelper

The old names isIgnoringBatteryOptimizations() / requestIgnoreBatteryOptimizations() remain as aliases. On iOS everything is a no-op (true / false).

// One call: standard battery request -> vendor-specific autostart guide.
final out = await OemBackgroundHelper.ensureBackgroundPermission(
  context,
  appName: 'Fleet Tracker',
  // force: true,                       // show again even if already confirmed
  // texts: OemGuideTexts(title: 'Enable Autostart ({brand})', steps: {...}),
  // builder: (ctx, guide) => MyDialog(guide),   // your own UI; use guide.openSettings()/close()
);
print(out.batteryOptimizationIgnored); // standard permission granted?
print(out.guideShown);                 // dialog shown this time?

// Or manually:
final r = await bgLocation.openOemAutostartSettings();
// r.outcome: vendor (vendor autostart page) | fallback (app details) | none

Flow of ensureBackgroundPermission:

  1. If not yet exempt, show the system "ignore battery optimisation" dialog, wait for the user to return to the app, then re-check.
  2. On a vendor device (Xiaomi/POCO/Redmi, Oppo/Realme, Vivo/iQOO, Huawei/Honor, Samsung, OnePlus, Asus, Letv, HTC, Nokia, Tecno/Infinix/itel, Meizu) show an English guide dialog (AlertDialog, follows the app theme) with vendor-specific steps: turn on Autostart, set the battery saver to No restrictions, lock the app in Recent apps. Open settings opens the vendor page.
  3. Vendors expose no API to read the Autostart state, so the dialog has a checkbox "I've set it up, don't remind me again". The choice is stored in native SharedPreferences (no shared_preferences package) so the dialog does not keep appearing. force: true or OemBackgroundHelper.resetGuide() shows it again.

openOemAutostartSettings() tries a candidate list of components per vendor (e.g. ColorOS old/new com.coloros.safecenter → com.oplus.safecenter → com.coloros.oppoguardelf, Vivo com.vivo.permissionmanager → com.iqoo.secure, Huawei startupmgr → optimize.process.ProtectActivity, OnePlus, Asus, Letv, …). Each candidate is checked with PackageManager.resolveActivity and started in a try/catch; if none opens → ACTION_APPLICATION_DETAILS_SETTINGS (OemSettingsOutcome.fallback).

Notes:

  • Android 11+ package visibility is handled with a <queries> block (22 vendor packages) in the plugin manifest, without QUERY_ALL_PACKAGES. If you add candidates in OemHelper.kt, add their packages to <queries>.
  • Samsung: the real Device Care package is com.samsung.android.lool (not looper); com.samsung.android.looper/...OverviewActivity from the first draft stays as the last candidate but is most likely absent and is skipped automatically.
  • Vendor activity names are unofficial and change between ROM versions; the list is best effort.
  • The service stays stopWithTask=false, foregroundServiceType="location", START_STICKY.

Per-brand reference: https://dontkillmyapp.com.

Customization #

Everything a user sees can be changed, and everything is optional: the defaults reproduce the behaviour of earlier versions.

What API Platform
Notification texts, live-text format, location-off text NotificationConfig.title/text/liveTextTemplate/liveTitleTemplate/locationDisabledText/subText/mockLabel Android
Notification icons, colour iconName, largeIconName, color, colorized Android
Channel channelId/channelName/channelDescription/importance/showBadge Android 8+
Lock screen, pinning, expand, timestamp visibility, ongoing, bigText, showTimestamp Android
Tap on the notification tapAction (openApp/deepLink/none) + tapDeepLink Android
Buttons actions: [NotificationAction.stop/openApp/deepLink/event] (max 3) Android
Update while tracking updateNotification(config), setNotificationText(...), clearNotificationText() Android (iOS: no-op)
Permission flow texts and UI LocationPermissionFlow.run(context, texts:, promptBuilder:, skip:) both
Own permission UI permissionState(), requestPermission(), requestBackgroundPermission(), openAppSettings() both
Play disclosure texts / UI BackgroundDisclosureTexts, BackgroundDisclosureBuilder both
Battery / OEM guide OemGuideTexts, OemGuideBuilder Android
Resume notification restart.resumeTitle/resumeText/resumeChannelName Android
Diagnostics wording HealthStatus.warningsWith(HealthWarningTexts(...)) both
iOS permission strings your Info.plist (see below) iOS

Foreground-service notification #

await bgLocation.startService(
  config: LocationConfig(
    notification: NotificationConfig(
      title: 'Delivery in progress',
      text: 'Waiting for GPS...',
      subText: 'Fast Courier',
      iconName: 'ic_stat_courier',      // white-on-transparent drawable of your app
      largeIconName: 'courier_logo',    // optional drawable/mipmap
      color: 0xFF00897B,                // ARGB; Colors.teal.toARGB32()
      colorized: true,
      channelId: 'courier_tracking',
      channelName: 'Courier tracking',
      channelDescription: 'Shown while your position is being shared',
      importance: NotificationImportance.low,
      visibility: NotificationVisibility.public,
      // Live text. Placeholders: {lat} {lng} {accuracy} {speedKmh} {speedMs} {speedMph} {bearing}
      // {altitude} {provider} {time} {battery} {satellites} {used} {mock} {mockSuffix}
      liveTextTemplate: '{speedKmh} km/h · ±{accuracy} m · {time}',
      liveTitleTemplate: 'Driving {speedKmh} km/h',
      mockLabel: 'FAKE GPS',
      liveUpdateIntervalMs: 3000,
      locationDisabledText: 'GPS is off - please turn it on',
      tapAction: NotificationTapAction.deepLink,
      tapDeepLink: 'myapp://delivery/current',
      actions: [
        NotificationAction.stop(label: 'End delivery'),
        NotificationAction.openApp(label: 'Open'),
        NotificationAction.event(id: 'pause', label: 'Pause'),
      ],
    ),
  ),
);

// React to the `event` button (the app does not open):
bgLocation.statusStream.listen((e) {
  if (e['status'] == 'notificationAction' && e['message'] == 'pause') { /* ... */ }
});

// Change it later without restarting tracking:
await bgLocation.updateNotification(const NotificationConfig(title: 'Delivery paused'));
// ...or just show your own text until you clear it:
await bgLocation.setNotificationText(title: 'Trip 12', text: '3.2 km so far');
await bgLocation.clearNotificationText();
  • Icons are resource names of the host app (drawable first, then mipmap). The plugin also ships a monochrome pin: iconName: 'fgbl_ic_location'. A missing resource is never fatal: the app launcher icon is used, an error event notificationIconMissing is emitted once, and healthCheck().notificationIconResolved / notificationLargeIconResolved turn false (also listed in HealthStatus.warnings). Keep the status-bar icon a white silhouette on a transparent background, otherwise Android draws a solid square.
  • Release builds with shrinkResources true remove drawables that are only referenced by name from Dart. Add android/app/src/main/res/raw/keep.xml: <resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@drawable/ic_stat_*,@drawable/courier_logo" />
  • importance (and the channel sound/vibration) is frozen by Android once a channel exists on the device. To apply a different importance, change channelId. Name and description update in place.
  • event buttons report on statusStream (status: notificationAction, message: <id>); openApp buttons start your launcher activity with the string extra fgbl_action = the action id.
  • updateNotification replaces the notification settings that are stored for automatic restarts and re-posts the notification immediately; the tracking engine is not restarted. updateConfig still restarts tracking.
  • iOS has no persistent notification (iOS shows the blue status-bar indicator), so NotificationConfig does nothing there.

Permission flow #

LocationPermissionFlow is an optional ready-made flow: device location switch → rationale → system prompt → (permanently denied: settings page) → Play disclosure → "Allow all the time" hint (Android) → notification permission → activity recognition. Every dialog text is a PermissionPrompt ({app} is substituted); set a prompt to null to drop that dialog, list steps in skip, or draw all dialogs yourself with promptBuilder. Run it before startService (see Quick start).

final result = await LocationPermissionFlow.run(
  context,
  appName: 'Fast Courier',
  texts: const PermissionFlowTexts(
    rationale: PermissionPrompt(
      title: 'Where are you?',
      body: '{app} needs your position to assign parcels. Choose "While using the app" next.',
      confirm: 'Got it',
      cancel: 'Later',
    ),
    backgroundSettings: PermissionPrompt(
      title: 'One more step',
      body: 'Pick "Allow all the time" so {app} keeps working with the screen off.',
      confirm: 'Open settings',
    ),
    notification: PermissionPrompt(title: 'Notifications', body: 'We show a tracking notification.'),
    disclosure: BackgroundDisclosureTexts(purpose: 'track your delivery route'),
  ),
  // Optional: your own UI for every step (return true to continue).
  promptBuilder: (context, step, prompt) => showMyBottomSheet(context, step, prompt),
);
if (result.completed) { /* permission is "always" */ }

Prefer your own screens? Skip the class and use the granular API:

final s = await bgLocation.permissionState();
// s.location (denied / deniedForever / whileInUse / always), s.canAskAgain, s.permanentlyDenied,
// s.locationServicesEnabled, s.notificationsEnabled, s.batteryOptimizationIgnored, s.preciseLocation
if (s.permanentlyDenied) await bgLocation.openAppSettings();
else if (!s.foregroundGranted) await bgLocation.requestPermission();
else if (!s.backgroundGranted) await bgLocation.requestBackgroundPermission();

What cannot be customised: the system permission dialogs themselves (Android and iOS draw and word them) and the iOS strings inside them (below).

iOS Info.plist strings #

iOS shows these strings verbatim, so they belong to your app and cannot be supplied by the plugin:

Key Needed for
NSLocationWhenInUseUsageDescription required, foreground location
NSLocationAlwaysAndWhenInUseUsageDescription required, "Always" upgrade
NSLocationAlwaysUsageDescription recommended (iOS < 11 / fallback)
NSMotionUsageDescription recommended (motion / still detection)
NSLocationTemporaryUsageDescriptionDictionary only for requestTemporaryFullAccuracy
UIBackgroundModes → location required for background tracking

Suggested wording lives in IosUsageDescriptions.suggestions. Translate them with InfoPlist.strings per language. await bgLocation.checkIosUsageDescriptions() reports at runtime which required keys or the location background mode are missing (always complete on Android).

Other texts #

  • Diagnostics: health.warningsWith(const HealthWarningTexts(locationOff: 'GPS is off', ...)).
  • Battery / OEM guide dialog: OemGuideTexts and OemGuideBuilder (see the OEM section).
  • Tap-to-resume notification after a blocked restart: RestartConfig(resumeTitle:, resumeText:, resumeChannelName:).
  • Everything else the plugin emits is machine-readable (event names, error codes) and never shown to users.

Field testing #

Use the example app (example/) or your own app. The example shows the filtered position with its quality, motion and indoor state, the motion stream, heartbeats, healthCheck() and the status events (priorityChanged, stillProbe, watchdogRestart, ...). For deeper checks log rawLocationStream, filterResultStream and rejectedFixStream in your app.

  1. Open sky: warm-up done in < 10 s, accuracy 2–5 m, HDOP < 1.5, usedInFix ≥ 10.
  2. Urban canyon: watch rejectedJump / rejectedHdop / rejectedSpeedJump; compare the raw and filtered tracks (sendFiltered: false on one phone).
  3. Doze 30–60 min: adb shell dumpsys deviceidle force-idle, then unforce; check that healthCheck().fixCount grows and backgroundIsolateRunning = true.
  4. App closed: swipe it from recents; the notification stays, data keeps being sent once (check the server for duplicates).
  5. Hard kill: adb shell run-as <pkg> kill -9 <pid> (debuggable build); the keep-alive alarm should bring the service back within keepAliveMs.
  6. Offline: airplane mode for 5 minutes; the queue drains after reconnecting.
  7. Mock GPS: with a mock-location app isMock = true, mockScore = 1. Developer options alone must show mock: no. A phone lying still must not accumulate imuStationaryButMoved accusations.
  8. iOS force-quit: swipe the app away, then move 200–500 m; the app must be relaunched and data must flow again.
  9. Drive mode (0.6.0): drive 2+ minutes; driveMode turns on within ~20 s above 15 km/h (immediately with the OS vehicle activity once above 10 km/h) and stays on through a red light shorter than 60 s. With a RoadSnapper the payload gains snapped* keys; with driveActivityType set, iOS keeps updating on unmapped roads (check this - see the risk above).
  10. Vendor autostart: on Xiaomi/Oppo/Vivo/Samsung call openOemAutostartSettings(); the vendor page must open (otherwise the app-details fallback) and the dialog must not return once confirmed.

Limitations #

  • Force stop (Settings → Force stop) on Android kills all components until the app is opened again. Restart through an alarm / boot can be refused by Android 12+ when the "all the time" permission is missing.
  • The background isolate contains only this plugin; other plugins cannot be called there.
  • If the background isolate fails to start, raw fixes are buffered (max 1000) and healthCheck().warnings reports it; there is no native upload fallback (deliberately, for the single owner).
  • The EKF uses position + Doppler speed from the chipset; a position solution from raw pseudorange / carrier phase is not implemented (GnssMeasurement is used for quality metrics and the speed-uncertainty floor).
  • HDOP is computed from satellite azimuth/elevation (single clock-bias approximation); iOS has no HDOP, so it always takes the accuracy fallback.
  • The IMU heuristic can false-positive when a phone lies still but the GPS fix jumps far (large multipath); that is why one layer alone never sets mockSuspected. It can false-negative when a spoofer also shakes the phone.
  • Play Integrity needs Google Play Services + a Cloud project linked in Play Console; the verdict is only valid when decoded on the server.
  • uuid / seq only guarantee dedup/order if your server uses them; the 4xx bisect uses a few extra requests (≈ 2·log₂ n) when one record is bad; the start pre-check uses process importance (IMPORTANCE_VISIBLE) as the "app is in the foreground" signal – the OS still decides (failures are reported); wifiOn is Android only.
  • setAlarmClock shows an alarm icon; SCHEDULE_EXACT_ALARM can be denied by the user (then only restartBlocked + a tap-to-resume notification). flushLocations() on Android is best effort (asynchronous in Play Services). Batching makes fixes arrive in groups (IMU/GNSS data only on the newest fix; motion is only noticed through activity recognition or when the batch arrives, at most maxUpdateDelayCapMs). BGAppRefreshTask cannot be guaranteed to run; a CLBackgroundActivitySession cannot be created when the app is relaunched in the background.
  • Indoor: coarse / held fixes are best-effort estimates, not real GPS; there is no PDR dead-reckoning (no heading / step length): the position is held, not predicted. Barometer floors are relative (weather drift is absorbed slowly, AC / doors can pulse the pressure) and need calibration for absolute floor numbers. A large jump agreed on by accurate fixes without IMU motion is still held.
  • iOS: no satellite / C/N0 / HDOP data (the indoor score uses accuracy and IMU only), CMAltimeter gives relative altitude since updates started, there is no update interval (balanced = 5 m distance), no permanent notification; relaunch after a force-quit relies on SLC / geofence (latency in minutes, not seconds); 20 regions per app (the plugin uses one).

API summary #

API Description
startService({config}) / stopService() / updateConfig(config) Control the service (+ background isolate)
setPreset(TrackingPreset, {overrides}) / LocationConfig.forPreset(...) / preset Battery / accuracy presets, switched live without a restart
warmUpGnss({timeout, targetAccuracyM, requireNetwork, refreshAssistance}) Optional GNSS warm-up before going offline (GnssWarmUpResult)
LocationConfig.warmUp (GnssWarmUpConfig) Optional autoWarmUpBeforeStart (default off)
HealthStatus.lastGnssFixAt / gnssDataAge / isGnssDataStale() Age of the last real GNSS fix (warn when stale, e.g. > 4 h)
isRunning() / healthCheck() Status & diagnostics (backgroundIsolateRunning, imuActive, …)
positionStream (locationStream) Filtered fixes (from the background isolate)
rawLocationStream / filterResultStream Raw data + mock score & filter decisions
sendResultStream / statusStream Send results & native events
sendLocation({fix, extraFields, timeout}) / buildPayload(fix) Manual send (relay) & payload
clearQueue() Empty the persistent queue
requestIntegrityToken({cloudProjectNumber, requestHash}) Play Integrity token (Android)
checkPermission() / requestPermission() / requestBackgroundPermission() Location permission
requestNotificationPermission() / ensurePermissions() Other permissions
isBatteryOptimizationIgnored() / requestDisableBatteryOptimization() Battery-optimisation exemption (old aliases remain)
getManufacturer() / needsOemAutostart() / openOemAutostartSettings() OEM helpers (Android)
OemBackgroundHelper.ensureBackgroundPermission(context, …) Battery permission + vendor guide dialog (+ resetGuide())
snappedFixStream / driveMode Road-snapped fixes (needs a RoadSnapper), last known drive-mode state
runFlutterGetBackgroundLoc({roadSnapper}) Call from your own background entry point (backgroundEntrypoint)
rejectedFixStream / motionStream / heartbeatStream Rejected fixes + reason, motion state (still/moving), heartbeat
checkActivityRecognitionPermission() / requestActivityRecognitionPermission() Activity recognition / Motion & Fitness permission
calibrateFloor(floor) Calibrate the floor number (barometer reference)
BackgroundLocationDisclosure.requestWithDisclosure(context, …) Play disclosure → location → background permission
LocationPermissionFlow.run(context, texts:, promptBuilder:, skip:) Customisable full permission flow
permissionState() / checkIosUsageDescriptions() Granular permission snapshot / iOS Info.plist check
updateNotification(config) / setNotificationText(...) / clearNotificationText() Change the notification while tracking
canScheduleExactAlarms() / openExactAlarmSettings() Exact alarms (Android 12+ restart)
flushLocations() / flushQueue() Deliver the OS batch / upload the queue now
requestTemporaryFullAccuracy(purposeKey) iOS: temporary precise accuracy (full/reduced)
FlutterGetBackgroundLocPlugin.registerBackgroundRefresh(identifier:) (Swift) Optional: BGAppRefreshTask queue retry
openAppSettings() / openLocationSettings() / getLastKnownFix() Utilities
FlutterGetBackgroundLocPlugin.restoreOnLaunch() (Swift) Resume tracking on iOS relaunch

Development #

flutter pub get
flutter analyze
flutter test                       # EKF, gating, indoor/held/anchor, motion, barometer, mock, upload
dart format --line-length 100 lib test example/lib example/test
cd example && flutter run          # example app
cd example && flutter build apk --debug
cd example && flutter build ios --no-codesign --debug

License #

MIT, see LICENSE.

1
likes
0
points
287
downloads

Publisher

verified publisherabedputra.my.id

Weekly Downloads

Accurate background location for Flutter with GNSS quality metrics, fake-GPS detection, adaptive Kalman filtering and offline-safe uploads.

Repository (GitHub)
View/report issues

Topics

#location #gps #geolocation #background #tracking

License

unknown (license)

Dependencies

flutter, plugin_platform_interface

More

Packages that depend on flutter_get_background_loc

Packages that implement flutter_get_background_loc