DEV Community

Cover image for background_location_free: background location on Android without a licence key
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

background_location_free: background location on Android without a licence key

A running tracker, a delivery app or a trip recorder has one requirement that ordinary location plugins do not meet: the positions must keep coming after the user leaves the app. On Android the supported way to do that is a foreground service with a visible notification, and the rules around it have become stricter with every release.

The README of background_location_free is direct about why it exists. flutter_background_geolocation is maintained, but Android release builds need a paid licence. background_locator_2 has had no release since 2023. This plugin does one job, a location foreground service, and nothing else. It is MIT licensed, needs no licence key, and does not depend on Google Play services.

What it does

A foreground service of type location. It shows a notification you configure: title, text, icon, channel, colour and whether it is ongoing. You can change the title and the text while the service runs.

LocationManager providers only. It uses gps, network and passive, so it works on de-Googled devices.

A stream of fixes. Stream<LocationFix> gives latitude, longitude, accuracy, altitude, speed, bearing, time, provider and a mock flag (Location.isMock() on API 31 and later, isFromMockProvider() before).

A native filter. fastestInterval and minDistanceMeters are enforced in the plugin, because LocationManager treats both as hints.

A native ring buffer. It keeps fixes in app storage while no Dart listener is attached. drainBuffered() empties it.

Headless delivery (experimental). A top-level Dart callback runs in a background FlutterEngine when the UI is gone.

Status. status() reports the location, precise, background and notification permissions, whether location services are on, and the battery-optimisation state.

Optional restart. restartOnBoot restarts tracking after a reboot or an app update. lastKnown() returns the newest cached fix across providers.

How to use it

Add it from GitHub:

dependencies:
  background_location_free:
    git: https://github.com/AbdeldjalilChougui/background_location_free
Enter fullscreen mode Exit fullscreen mode

minSdk is 21, and you build with compileSdk 34 or newer.

The manifest

The plugin's own manifest already adds FOREGROUND_SERVICE, FOREGROUND_SERVICE_LOCATION, the service with android:foregroundServiceType="location", and a disabled boot receiver. Your app adds the rest:

  • ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION are required. On Android 12 and later the user can grant approximate location only, and that still works.
  • POST_NOTIFICATIONS is recommended on Android 13 and later. Without it the service still runs, but its notification only shows in the Task Manager, not in the drawer.
  • ACCESS_BACKGROUND_LOCATION is needed only when the service is started or restarted while no activity is visible: after a reboot, after an app update, or when the system restarts a killed service. You do not need it when tracking starts from the UI and the service keeps running.
  • RECEIVE_BOOT_COMPLETED is needed only for restartOnBoot: true.

Permissions

The plugin never asks for permissions. You request the runtime ones with a permissions plugin, and the README suggests android_special_permissions for the battery-optimisation and background-location Settings screens. status() tells you where you are, and the README has a flow chart: foreground location first, then location services, then notifications, then (only if needed) an in-app disclosure and the background permission, and finally start() while an activity is visible.

Dart

import 'package:background_location_free/background_location_free.dart';

Future<void> startTracking() async {
  final status = await BackgroundLocation.status();
  if (!status.canStart) return; // request permissions first

  await BackgroundLocation.start(LocationConfig(
    interval: const Duration(seconds: 5),
    fastestInterval: const Duration(seconds: 2),
    minDistanceMeters: 10,
    priority: LocationPriority.highAccuracy,
    notification: const NotificationConfig(
      title: 'Recording your run',
      text: 'Tap to open',
      iconResource: 'ic_stat_location',
      channelId: 'tracking',
      channelName: 'Tracking',
      color: 0xFF2E7D32,
    ),
    stopOnTaskRemoved: false,
  ));

  final sub = BackgroundLocation.locations.listen((fix) {
    print('${fix.lat}, ${fix.lon} ±${fix.accuracy} m via ${fix.provider}');
  });

  await BackgroundLocation.updateNotification(text: '3.2 km so far');

  // Later:
  await sub.cancel();
  await BackgroundLocation.stop();
}

Future<void> onAppResumed() async {
  // Fixes recorded while nothing listened, oldest first.
  final missed = await BackgroundLocation.drainBuffered();
  print('caught up on ${missed.length} fixes');
}
Enter fullscreen mode Exit fullscreen mode

The error codes on BackgroundLocationException.code are permission_denied, start_not_allowed (Android 12 and later refused a start from the background), no_provider, invalid_config, not_running and start_timeout. The stream can also emit provider_disabled when the user turns a provider off.

Where each fix goes

For each fix that passes the filter, the service picks one destination:

  1. If a Dart listener is attached to locations, the fix goes there.
  2. Otherwise, if a headless callback is registered, the callback runs.
  3. Otherwise the fix goes to the ring buffer (bufferCapacity, 1000 by default; the oldest fixes are dropped first).

Buffered fixes are not replayed on the stream automatically. Call drainBuffered() when your UI comes back.

The headless callback

@pragma('vm:entry-point')
Future<void> onBackgroundFix(LocationFix fix) async {
  // Runs in a separate isolate: no access to UI state. Keep it short.
}

await BackgroundLocation.registerHeadlessCallback(onBackgroundFix);
Enter fullscreen mode Exit fullscreen mode

If the callback's handle does not resolve, or the callback throws, the fix goes to the ring buffer, so it is not lost. Callback handles can change between app builds, so call registerHeadlessCallback on every app start.

Things to know

  • Android only. On other platforms every call throws MissingPluginException.
  • Android's rules still apply. Apps targeting Android 12 or higher cannot start a foreground service from the background, apart from listed exemptions; the plugin reports this as start_not_allowed. A location service cannot be created in the background without ACCESS_BACKGROUND_LOCATION. From Android 14, users can dismiss the notification even if it is ongoing; the service keeps running. The README links the Android documentation for each rule.
  • Google Play declarations. Apps targeting Android 14 and later declare each foreground service type in Play Console. If you declare ACCESS_BACKGROUND_LOCATION, you also fill in the location permissions declaration, with a prominent in-app disclosure, a short video and a privacy policy. Apps that start tracking only from the UI can leave that permission out and avoid the second declaration.
  • Battery optimisation. Doze and OEM battery managers can delay or kill even a foreground service. status().batteryOptimizationExempt tells you whether the app is exempt. Play policy allows asking for the exemption directly only when the core function of the app is affected.
  • What it does not do. No geofencing, no activity recognition or stop detection, no iOS, no Fused Location Provider, no permission requests, no HTTP upload, and no persistence beyond the ring buffer.
  • One provider per session. highAccuracy uses gps (with network as a fallback when GPS is absent), so indoor fixes can be slow. balanced and lowPower use network, which some de-Googled ROMs lack. GPS and network fixes are not merged.
  • Headless mode is experimental.
  • restartOnBoot has conditions. It restarts only when tracking was running and the app holds location permission, plus the background permission on Android 10 and later. It does not survive a force stop.
  • What was tested. The Kotlin logic (config parsing, the ring buffer, the distance and interval filter, API-level branching, routing) has JUnit tests, and the Dart API has mocked-channel tests. The example app has an emulator integration test that checks status(), the error codes, that the service runs in the foreground with type location, fixes injected with adb emu geo fix, a mock provider, updateNotification, buffering with drainBuffered(), the headless callback while the UI is in the background, and stop().
  • What was not tested end to end. restartOnBoot after a real reboot, a sticky restart after the process is killed, and the headless callback after the task is swiped away from Recents. Everything ran on the Android emulator (Pixel 10 image, API 37); a physical phone was not tested.

Why I built it

The README states the gap in two sentences: the maintained option needs a paid licence for Android release builds, and the free one has not had a release since 2023. In the meantime Android added foreground service types, background start restrictions and new notification behaviour, and a plugin that does not follow them fails at start-up or in Play review.

I did not want another large tracking framework. I wanted the smallest piece that is hard to write correctly: a location foreground service that follows the current Android rules, filters fixes natively, and does not lose them when no Dart code is listening. Permissions, uploads, throttling and storage are left to the app or to other packages, and the README says so in a "What this does NOT do" section. Using LocationManager only keeps the plugin free of a Play services dependency, at the cost of the limits listed above.

Get the code

The source, the manifest guide, the permissions flow chart, the example app and the tests are on GitHub: https://github.com/AbdeldjalilChougui/background_location_free. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)