flutter_get_background_loc

pub package pub points likes platform CI License: MIT style: flutter_lints

Demo: live tracking with filtered accuracy, satellites and the battery vs accuracy chart

Live demo on an Android phone: filtered vs raw accuracy, satellites, C/N0 and the battery vs accuracy chart. Click the preview for the full 1:37 video.

A Flutter plugin for accurate background location on Android and iOS. No dependencies besides Flutter's plugin_platform_interface.

Features

  • Background tracking that survives: Android foreground service with restart after swipe-away, keep-alive alarm, optional start on boot and a provider watchdog; iOS relaunch after force-quit.
  • One owner, no double uploads: native code only delivers raw fixes; a headless background Dart isolate filters and uploads.
  • Kinematic adaptive EKF with quality gating, a stationary anchor against still drift and graceful indoor output (good / degraded / coarse / held).
  • GNSS quality (Android): satellites, C/N0, HDOP, full tracking, Doppler uncertainty.
  • Mock-location detection without QUERY_ALL_PACKAGES: OS flags, IMU-vs-GNSS check, teleport detection, Play Integrity tokens.
  • Battery / accuracy presets switchable at runtime, low power while still, optional GNSS warm-up.
  • Persistent upload queue with backoff, uuid + seq per record, batching and Wi-Fi-only options.
  • Indoor score, motion state, drive mode, barometer floors, heartbeat. Every feature can be switched off and then starts nothing.
  • Stationary lock (0.12.0 / 0.13.x): while still, the last published point is pinned; GNSS cannot leave still alone. 0.13.0 adds a fast start-in-still when activity recognition and the IMU agree, a startup publish hold, a post-unlock release gate, a provisional initial location at Start (coarse first fix, later refined, neither hop on the odometer), activity-watchdog backoff and still-probe backoff. 0.13.1 ignores Doppler transients after GNSS re-acquisition, requires IMU / activity / sustained Doppler before Doppler alone can wake the lock, arms the release gate after any wake, and only odometers corroborated net displacement (wakeSource is reported on every fix). 0.13.2 keeps the odometer across a GNSS-gap reset, releases a vehicle from the previous raw fix (plus a Doppler fast path), and caps a smooth accuracy-spike reject run. 0.13.3 credits a post-wake hop only when it is a residual snap (default cap 40 m) and arms the still probe with AlarmManager so it survives Doze. 0.13.4 starts the still probe in the foreground when tracking should already be on (otherwise it is delivered through a receiver, never as a cold start), credits a hop above the cap only with motion evidence or a young pin, does not publish a mid-trip initialCoarse after a keep-odometer reset, uses setExactAndAllowWhileIdle when exact alarms are permitted, trusts Doppler at 1.5 m/s accuracy or speed / speedAccuracy >= 3, requires a second source after an IMU-only wake following a long still, and keeps the published point on the pin while locked (pinPublishedWhileLocked, default true), with distance, max-hold and IMU-sustained release paths so a real departure is not held. A hop above the cap (for example the first fix after a GNSS gap while driving) is added to the odometer only after the next 2 accepted fixes stay away from the old pin (odometerConfirmLargeHop, default true): a real drive during the gap is still counted, a lone bad far fix is not. dart run tool/replay_published.dart replays the engine over a raw-fixes CSV; REPLAY_FILTER_JSON and REPLAY_MOTION_JSON override defaults. Configurable wakes and defaults: motion and power, filtering, configuration.

Installation

flutter pub add flutter_get_background_loc

or in pubspec.yaml:

dependencies:
  flutter_get_background_loc: ^0.13.4
import 'package:flutter_get_background_loc/flutter_get_background_loc.dart';

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

Permissions, the foreground service and the receivers come from the plugin manifest (merged automatically). minSdk 24. Google Play Services is used for the fused provider (raw GPS fallback). Publishing on Google Play needs the background-location declaration; see Platform setup.

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>

and call FlutterGetBackgroundLocPlugin.restoreOnLaunch() in AppDelegate.swift (before GeneratedPluginRegistrant.register) so tracking resumes after a background relaunch. iOS 15.0 minimum. Details: Platform setup.

Quick start

Run the permission flow from a widget (it needs a BuildContext) before startService:

final bgLocation = FlutterGetBackgroundLoc();

// 1. Permissions: in-app dialogs, then the system prompts
final perm = await LocationPermissionFlow.run(context, appName: 'My App');
if (!perm.completed) return;

// 2. Start tracking with a preset (optional upload to your server)
await bgLocation.startService(
  config: LocationConfig.forPreset(
    TrackingPreset.balanced,
    base: const LocationConfig(
      notification: NotificationConfig(title: 'Tracking active', text: 'Location is on'),
      send: SendConfig(url: 'https://api.example.com/v1/locations'),
    ),
  ),
);

// 3. Filtered positions (processed by the background isolate)
bgLocation.positionStream.listen((fix) {
  print('${fix.latitude}, ${fix.longitude} ±${fix.accuracy} m, quality ${fix.quality?.name}');
});

// 4. Health and stop
final health = await bgLocation.healthCheck();
print(health.warnings);
await bgLocation.stopService();

When the app is opened again while the service is still running, just listen to positionStream again. The full example (raw stream, filter results, manual send, all options) is in the API summary; a runnable app is in example/.

Tracking presets

Preset Rate Still / anchored Expected accuracy Battery
powerSaver balanced power, 30 s / 25 m 60 s / 50 m ~20-50 m lowest
balanced (default) high accuracy, 1 s while moving balanced, 30 s / 20 m ~3-15 m medium
highAccuracy high accuracy, 1 s, full tracking never low power best available highest

Switch at runtime with setPreset(TrackingPreset.highAccuracy); no restart. Values are indicative; see Presets, motion & power and the Benchmarks.

Documentation

Topic Page
Architecture and design architecture.md
Android / iOS setup, permissions, Google Play, OEM battery killers platform-setup.md
Every config option and its default configuration.md
EKF, gating, anchor, indoor score, drive mode, road snapping filtering.md
Presets, low power, still probe, stationary lock, activity recognition, batching, restart motion-and-power.md
Upload, payload, queue, server dedup upload.md
GNSS warm-up gnss-warm-up.md
Mock-location detection, Play Integrity mock-detection.md
Notification, permission flow and texts customization.md
Battery vs accuracy screenshots benchmarks.md
Field testing and limitations troubleshooting.md
API summary api.md
Development and releasing releasing.md

Changes per version: CHANGELOG.

License

MIT, see LICENSE.

Libraries

flutter_get_background_loc
Accurate background location for Flutter.