All posts
FlutterGPS trackingBatteryTraccar

Adaptive location sampling in Flutter for better battery life

Nov 14, 20268 min read

The fastest way to get one-star reviews on a tracking app is to drain the battery. The second fastest is to save battery by recording so rarely that the route on the map looks like a straight line through buildings.

The fix is to stop using one fixed setting. A phone sitting on a desk for eight hours doesn't need a GPS fix every 10 seconds, but a car on a winding road does. Adaptive sampling means changing how often and how precisely you record based on what the device is doing.

This post shows a simple, practical version in Flutter using the geolocator package. It builds on the Traccar client from the previous post.

Where the battery actually goes

Three things decide most of the battery cost of location tracking:

  1. Accuracy. High accuracy turns on the GPS chip. Lower accuracy can use Wi-Fi and cell towers, which cost much less.
  2. How often the location engine wakes up. Every wake-up keeps the CPU and radios busy for a while.
  3. How often you send data. Each upload wakes the mobile radio, which stays in a high-power state for several seconds afterwards.

So the goal is to keep the GPS chip on only while the device is really moving, and to batch or slow down uploads when nothing is changing.

The plan: three modes

Mode When Accuracy Distance filter Interval (Android)
Moving speed above 5 m/s (18 km/h) High 30 m 10 s
Slow speed 0.5–5 m/s (walking, traffic) High 15 m 15 s
Stationary below 0.5 m/s for 3 minutes Low 100 m 5 min

Plus two extra rules:

  • Low battery (below 20% and not charging): use balanced accuracy and double the intervals.
  • Heartbeat while stationary: send the last position every 10 minutes, so the server still shows the device as online.

These numbers are a reasonable starting point, not magic. Tune them for your users: a delivery fleet and a family-safety app have very different needs.

Building the settings for each mode

geolocator takes platform-specific settings. On Android you need a foreground service notification to keep receiving locations with the screen off. On iOS you need background location mode enabled in Xcode (UIBackgroundModes → location) and "Always" permission.

import 'dart:io';
import 'package:geolocator/geolocator.dart';

enum TrackingMode { moving, slow, stationary }

LocationSettings settingsFor(TrackingMode mode, {required bool lowBattery}) {
  final (accuracy, distance, interval) = switch (mode) {
    TrackingMode.moving => (LocationAccuracy.high, 30, 10),
    TrackingMode.slow => (LocationAccuracy.high, 15, 15),
    TrackingMode.stationary => (LocationAccuracy.low, 100, 300),
  };

  final effectiveAccuracy =
      lowBattery && mode != TrackingMode.stationary ? LocationAccuracy.medium : accuracy;
  final effectiveInterval = lowBattery ? interval * 2 : interval;

  if (Platform.isAndroid) {
    return AndroidSettings(
      accuracy: effectiveAccuracy,
      distanceFilter: distance,
      intervalDuration: Duration(seconds: effectiveInterval),
      foregroundNotificationConfig: const ForegroundNotificationConfig(
        notificationTitle: 'Tracking active',
        notificationText: 'Your location is being shared',
        enableWakeLock: false,
      ),
    );
  }

  if (Platform.isIOS) {
    return AppleSettings(
      accuracy: effectiveAccuracy,
      distanceFilter: distance,
      activityType: ActivityType.automotiveNavigation,
      pauseLocationUpdatesAutomatically: false,
      allowBackgroundLocationUpdates: true,
      showBackgroundLocationIndicator: true,
    );
  }

  return LocationSettings(accuracy: effectiveAccuracy, distanceFilter: distance);
}

On iOS there's no "interval" setting. iOS delivers updates based on the distance filter and accuracy, which is why the distance filter does most of the work there.

Switching modes without flapping

GPS speed is noisy. A parked phone can report 0.3 to 1.5 m/s for a few seconds as the fix wanders. If you switch modes on every reading, the app will bounce between modes and waste more battery than a fixed setting.

There's a second trap: with a distance filter, a phone that isn't moving sends no updates at all. So "no movement for 3 minutes" can't be detected from readings. It has to be a timer that every real movement resets.

The rules:

  1. Ignore bad fixes. Drop any position with accuracy worse than 50 m before deciding anything.
  2. Stationary is a timer. If 3 minutes pass without a reading above 0.5 m/s, switch to stationary.
  3. Moving vs slow needs 3 readings in a row before switching, so one noisy speed value doesn't flip the mode.
  4. Waking up is position-based. In stationary mode, any update that is clearly away from where the device parked means it's moving. Don't rely on speed here: low-accuracy fixes often report no speed at all.

Here's the tracker:

import 'dart:async';
import 'package:battery_plus/battery_plus.dart';
import 'package:geolocator/geolocator.dart';

class AdaptiveTracker {
  AdaptiveTracker(this.queue); // PositionQueue from the previous post

  final PositionQueue queue;
  final _battery = Battery();

  StreamSubscription<Position>? _sub;
  Timer? _heartbeat;
  Timer? _stillTimer;
  TrackingMode _mode = TrackingMode.slow;
  TrackingMode? _candidate;
  int _candidateCount = 0;
  Position? _last; // last good fix; while stationary, where the device parked
  bool _lowBattery = false;

  Future<void> start() async {
    _lowBattery = await _isLowBattery();
    _listen();
    _battery.onBatteryStateChanged.listen((_) async {
      final low = await _isLowBattery();
      if (low != _lowBattery) {
        _lowBattery = low;
        _listen(); // re-subscribe with new settings
      }
    });
  }

  void stop() {
    _sub?.cancel();
    _heartbeat?.cancel();
    _stillTimer?.cancel();
  }

  void _listen() {
    _sub?.cancel();
    _sub = Geolocator.getPositionStream(
      locationSettings: settingsFor(_mode, lowBattery: _lowBattery),
    ).listen(_onPosition);

    _heartbeat?.cancel();
    _stillTimer?.cancel();
    if (_mode == TrackingMode.stationary) {
      _heartbeat = Timer.periodic(const Duration(minutes: 10), (_) => _sendHeartbeat());
    } else {
      _restartStillTimer();
    }
  }

  // A still phone sends no updates, so stillness is detected by a timer.
  void _restartStillTimer() {
    _stillTimer?.cancel();
    _stillTimer = Timer(const Duration(minutes: 3), () => _switchTo(TrackingMode.stationary));
  }

  void _onPosition(Position p) {
    if (_mode == TrackingMode.stationary) {
      // Wake up only when clearly away from the parking spot. Adding the fix's
      // own accuracy stops a wandering low-accuracy fix from waking us.
      final parked = _last;
      final moved = parked == null ||
          Geolocator.distanceBetween(parked.latitude, parked.longitude, p.latitude, p.longitude) >
              100 + p.accuracy;
      if (moved) _switchTo(TrackingMode.slow); // high accuracy will measure the real speed
      return;
    }

    if (p.accuracy > 50) return; // too inaccurate to trust
    _last = p;
    queue.add(queue.client.buildUri(p));

    final speed = p.speed < 0 ? 0.0 : p.speed;
    if (speed < 0.5) return; // standing still: let the timer decide
    _restartStillTimer();

    final next = speed > 5 ? TrackingMode.moving : TrackingMode.slow;
    if (next == _mode) {
      _candidate = null;
      _candidateCount = 0;
      return;
    }
    _candidateCount = next == _candidate ? _candidateCount + 1 : 1;
    _candidate = next;
    if (_candidateCount >= 3) _switchTo(next);
  }

  void _switchTo(TrackingMode mode) {
    _candidate = null;
    _candidateCount = 0;
    if (mode == _mode) return;
    _mode = mode;
    _listen();
  }

  Future<void> _sendHeartbeat() async {
    final p = _last;
    if (p == null) return;
    // Same place, fresh timestamp, so Traccar keeps the device "online".
    final base = queue.client.buildUri(p);
    await queue.add(base.replace(queryParameters: {
      ...base.queryParameters,
      'timestamp': (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString(),
      'speed': '0',
    }));
  }

  Future<bool> _isLowBattery() async {
    final level = await _battery.batteryLevel;
    final state = await _battery.batteryState;
    return level < 20 && state != BatteryState.charging && state != BatteryState.full;
  }
}

A few notes on the design:

  • Waking up is fast, going to sleep is slow. Missing the start of a trip looks bad on the map, so one update away from the parking spot is enough to wake up. Going to sleep needs three minutes without movement.
  • Changing settings means re-subscribing. geolocator streams can't change their settings, so _listen() cancels and starts a new stream. That's cheap, but don't do it on every reading, which is another reason for the 3-reading rule.
  • The first update after re-subscribing is ignored when parked. A new stream usually delivers a fix right away. Because it's at the parking spot, the distance check keeps the tracker asleep instead of waking it straight back up.
  • The heartbeat matters for Traccar. Traccar marks a device offline when it hasn't heard from it for a while (the status.timeout setting). Without a heartbeat, a parked vehicle looks "offline" and customers think the tracker broke.

Why the stationary distance filter is 100 m

In stationary mode the app relies on the OS to wake it when the device moves. A 100 m distance filter with low accuracy lets the OS use cheap Wi-Fi and cell positioning and only deliver an update after a real move. When one arrives, the tracker switches to slow mode, where high accuracy measures the real speed, and moves up to moving mode if the speed stays above 5 m/s.

The trade-off: the first 100 m or so of a trip may be recorded with low accuracy. For most fleets that's fine. If you need the exact start point, you can add activity recognition (the phone's motion sensors) to wake the GPS sooner, at the cost of more permissions and complexity.

Things that will still kill your battery

Adaptive sampling won't help if any of these are true:

  • Uploading every point on its own. In slow and stationary modes, consider queueing points and sending them together every minute or two. One radio wake-up is cheaper than ten.
  • Manufacturer battery savers. Xiaomi, Huawei, Samsung, OnePlus and others kill background apps aggressively. Ask users to set your app to "No restrictions" in battery settings. dontkillmyapp.com has per-brand instructions you can link to.
  • Wake locks. Leave enableWakeLock off unless you've measured that you need it.
  • Logging and analytics on every fix. Writing to disk or sending analytics events per position adds up.

Measuring the result

Don't trust feelings or anyone's blog post, including this one. Measure on real devices:

  1. Fully charge two identical phones (or the same phone on two days).
  2. Run the fixed-interval build on one and the adaptive build on the other, in the same daily routine.
  3. Compare battery percentage used per hour, and check Settings → Battery to see your app's share.
  4. Open both routes in Traccar and check that the adaptive one still looks right on corners.

If the route quality drops, lower the distance filter in moving mode. If battery is still too high, look at upload batching first.

Summary

  • Use high accuracy and short intervals only while moving.
  • Drop to low accuracy and a 100 m distance filter when stationary for a few minutes.
  • Filter out inaccurate fixes and use hysteresis so modes don't flap.
  • Send a heartbeat while parked so Traccar shows the device as online.
  • Batch uploads and handle manufacturer battery savers.
  • Measure on real devices and tune the numbers for your users.

Keep reading

Need help with your Traccar server?

I offer Traccar setup and maintenance, GPS tracking apps and Flutter development.