Sub topic 13
Background location and its extra requirements
This chapter assumes you can already run the check-then-request flow from earlier chapters. It also assumes you know the LocationPermission states, can read a position stream with geolocator, and can edit AndroidManifest.xml and Info.plist. Here you add the pieces that let an app keep receiving positions after the user leaves it.
What "background" means
Foreground location works while your app is visible. Background location keeps working when the app is minimized or the screen is locked. Both platforms treat this as a stronger capability than normal location access:
- The user must grant a separate, broader permission.
- The platform must be told the app intends to run in the background.
- The user must be able to see that tracking is active (a notification on Android, a status bar indicator on iOS).
- The app store reviews the request.
Most apps do not need it. A "nearby places" screen only needs the position while it is open. Background access is for turn-by-turn navigation, fitness tracking, delivery tracking, and similar features where the user expects tracking to continue with the screen off.
Permission levels
| Concept | Android | iOS | geolocator value |
|---|---|---|---|
| Foreground only | `ACCESS_FINE_LOCATION` / `ACCESS_COARSE_LOCATION` | "While Using the App" | `LocationPermission.whileInUse` |
| Also in background | `ACCESS_BACKGROUND_LOCATION` ("Allow all the time") | "Always" | `LocationPermission.always` |
On Android, LocationPermission.always means the background permission is granted. On iOS, it means the user chose "Always".
Declaring the requirements
Android
Add the background permission and the permissions for a foreground service of type location. Android stops or throttles location delivery to background apps unless a foreground service is running, so a plugin that tracks in the background needs one.
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application ...>
...
</application>
</manifest>What each new entry does:
ACCESS_BACKGROUND_LOCATIONexists from Android 10 (API 29). It is the permission the user sees as "Allow all the time".FOREGROUND_SERVICEis required for foreground services from Android 9 (API 28).FOREGROUND_SERVICE_LOCATIONis required from Android 14 (API 34) for a service of typelocation.POST_NOTIFICATIONSis a runtime permission from Android 13 (API 33). Without it, the user may not see the foreground service notification. The service still runs, but the notification can be hidden in the notification drawer.
The geolocator_android package ships its own location service. Check its README for your installed version to confirm what it declares. If you write your own service, declare it with android:foregroundServiceType="location".
iOS
Add the "always" usage description and the location background mode. Keep the when-in-use string from earlier chapters, because iOS shows both descriptions in different dialogs.
<key>NSLocationWhenInUseUsageDescription</key>
<string>We use your location to show nearby places while the app is open.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We record your route during a run, even when the screen is locked.</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>Without UIBackgroundModes containing location, iOS suspends your app shortly after it leaves the foreground, and no positions arrive. You can also enable it in Xcode under Signing & Capabilities, Background Modes, "Location updates".
Requesting background permission in two steps
On Android 11 (API 30) and later, you cannot ask for foreground and background location in the same request. You must request foreground permission first, and only after it is granted request background permission. The system does not show a normal dialog for the second step. It sends the user to a settings screen where they pick "Allow all the time".
iOS follows a similar order. The user first picks "While Using the App" and may later be offered an upgrade to "Always". iOS decides when that upgrade prompt appears, and you cannot force it.
import 'package:permission_handler/permission_handler.dart';
Future<bool> ensureAlwaysLocation() async {
final foreground = await Permission.locationWhenInUse.request();
if (!foreground.isGranted) {
return false;
}
final background = await Permission.locationAlways.request();
if (background.isGranted) {
return true;
}
if (background.isPermanentlyDenied) {
await openAppSettings();
}
return false;
}If you call Permission.locationAlways.request() before foreground permission is granted, the call fails on Android 11 and later. Always keep the two-step order, even if you only care about the final result.
flowchart TDThe block above is only a placeholder name for the flow described next. The real diagram follows.
Showing a rationale before the second step
The background request is the one users refuse most often, because "Allow all the time" sounds alarming. Show your own screen before sending them to settings. It should say:
- what feature depends on it (for example, "record your run with the screen off"),
- what you do not do (for example, "we only track while a run is active"),
- that they can change the choice later.
Google Play expects an in-app disclosure before the background request. Make the button label specific, such as "Continue to settings", so users know the next screen is not a normal dialog.
Streaming positions in the background
Permission alone is not enough. You also need to configure the position stream so each platform keeps it alive. geolocator provides platform-specific settings classes for this.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:geolocator/geolocator.dart';
StreamSubscription<Position>? _backgroundSubscription;
LocationSettings _backgroundSettings() {
if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 25,
foregroundNotificationConfig: const ForegroundNotificationConfig(
notificationTitle: 'Run in progress',
notificationText: 'Recording your route.',
enableWakeLock: true,
),
);
}
if (defaultTargetPlatform == TargetPlatform.iOS) {
return AppleSettings(
accuracy: LocationAccuracy.high,
activityType: ActivityType.fitness,
distanceFilter: 25,
pauseLocationUpdatesAutomatically: false,
showBackgroundLocationIndicator: true,
allowBackgroundLocationUpdates: true,
);
}
return const LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 25,
);
}
Future<void> startBackgroundTracking() async {
final permission = await Geolocator.checkPermission();
if (permission != LocationPermission.always) {
throw StateError('Background location is not granted.');
}
await _backgroundSubscription?.cancel();
_backgroundSubscription = Geolocator.getPositionStream(
locationSettings: _backgroundSettings(),
).listen((position) {
debugPrint('${position.latitude}, ${position.longitude}');
});
}
Future<void> stopBackgroundTracking() async {
await _backgroundSubscription?.cancel();
_backgroundSubscription = null;
}Points worth noting:
- Passing
ForegroundNotificationConfigmakes the plugin start an Android foreground service with a persistent notification. This notification is the visible sign that tracking is active. Users can see it, and Android requires it. enableWakeLockkeeps the CPU awake so updates continue with the screen off. It costs battery, so enable it only for use cases like workouts.allowBackgroundLocationUpdatestells iOS the app may receive updates while suspended. It only works ifUIBackgroundModescontainslocation.showBackgroundLocationIndicatorshows the blue status bar pill on iOS. Leave it on for a feature the user started, because it tells them tracking is running.pauseLocationUpdatesAutomatically: falsestops iOS from pausing updates when it thinks the user is stationary. For a fitness app that is usually the right choice. For a low-power feature, leave the default.distanceFiltermatters more in the background than in the foreground, because every update wakes your app.
Pitfalls specific to background location
- Android may ask again, or never. If the user denies the settings page choice,
permission_handlercan report permanent denial after a few attempts. Treat the settings redirect as the only path forward. - iOS users can downgrade later. iOS periodically reminds users that an app used their location in the background, and they can switch to "While Using". Run
Geolocator.checkPermission()when the app resumes and before starting a tracked session, never only once at install. - iOS "Allow Once" results in
whileInUsebehavior. Do not assume a granted permission persists across launches. - Battery optimizations on some Android manufacturers can kill services even with a foreground service. If tracking stops on certain devices, check the manufacturer's battery settings. You may need to guide users to exclude the app.
- Emulators and simulators. They can simulate routes, but they do not reproduce vendor battery management. Test long sessions on a physical device.
Store review
Both stores check background location.
- Google Play requires a Permissions Declaration form for
ACCESS_BACKGROUND_LOCATION. You describe the feature that needs it and usually provide a short video showing the in-app disclosure and the feature. Apps without a clear core need are rejected. - Apple App Review checks that
UIBackgroundModesincludeslocationonly when it is justified, and that your usage description string states a specific reason. Vague text like "We need your location" is a common cause of rejection.
If a feature can work with foreground access only, prefer it. You avoid the review burden, the scarier permission dialog, and the battery cost.
Summary of the decision
| Question | If yes | If no |
|---|---|---|
| Must tracking continue with the screen off? | Request background permission and run a foreground service | Use `whileInUse` only |
| Is it a one-time check (a geofence, a delivery arrival)? | Consider a platform geofencing or a single foreground read | Use a position stream |
| Is the user starting and stopping it explicitly? | Show the notification or indicator and cancel on stop | Reconsider the design |
Exercise
Your app already has LocationPermission.whileInUse on Android 12. A teammate calls Permission.locationAlways.request() and shows the result immediately. Why can the user see no normal dialog, and what should the code do when the result is isPermanentlyDenied?
Show answer
On Android 11 and later, the background permission is not granted through a normal dialog. The system sends the user to the app's location settings page, where they must choose "Allow all the time". If the user leaves without choosing it, the request returns denied, and after repeated refusals isPermanentlyDenied. At that point the app cannot ask again, so it should explain why the feature needs the setting, call openAppSettings(), and keep the feature disabled until checkPermission() returns LocationPermission.always after the app resumes.
Exercise
A background run tracker works while the screen is on, but on iOS no positions arrive after the app is minimized. Name two configuration items to check.
Show answer
Check that Info.plist has UIBackgroundModes containing location, and that the stream uses AppleSettings with allowBackgroundLocationUpdates: true. Also confirm the user granted "Always" rather than "While Using the App".