Background location tracking (.NET MAUI)

It's common on mobile devices for the operating system to suspend the execution of apps when they are not visible to the user (in the background, for example). Suspending such apps helps preserve resources and provides better security. For an app that relies on using the device location, be aware that background apps won't receive location updates from the system without additional configuration by the developer. If your app needs location updates while running in the background, you can configure it so the system will not suspend your app while location services are active.

Track location history

When to use background location tracking

For most mobile apps, location updates are only needed when the app is in the foreground. For example, a navigation app that provides turn-by-turn directions only needs to know the user's location when the app is open. In this case, you can use the default behavior of the operating system to suspend the app when it is not visible to the user.

However, some scenarios require location tracking even when the app is in the background.

For example, apps may need constant location updates when doing things like:

  • Recording the user's path while hiking, running, or cycling
  • Tracking a mobile worker's location relative to a geofence
  • Providing location-based notifications or alerts

Configure background location tracking

Android and iOS use different mechanisms to allow apps to receive location updates when they are not visible to the user. For each platform, you need to configure additional permissions for your .NET MAUI app. The following sections describe how to configure background location tracking for each platform.

Android

Android requires the use of a foreground service to track location in the background. Foreground services permit your app to asynchronously perform operations that are noticeable to the user (a status bar notification let users know that your app is executing an operation and consuming system resources).

Create a new class that defines an Android foreground service to provide location updates in the background. This class must inherit from Service and override the OnStartCommand method. The following example shows how to create a foreground service that provides location updates:

LocationService.cs
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
[Service(ForegroundServiceType = Android.Content.PM.ForegroundService.TypeLocation)]
public class LocationService : Service
{
    public override StartCommandResult OnStartCommand(Intent? intent, StartCommandFlags flags, int startId)
    {
        var notification = GetServiceStartedNotification(this);
        StartForeground(1, notification, Android.Content.PM.ForegroundService.TypeLocation);
        return base.OnStartCommand(intent, flags, startId);
    }
}

Add code like the following to the MainPage.xaml.cs file to create the SystemLocationDataSource:

MainPage.xaml.cs
Use dark colors for code blocksCopy
1
_locationDataSource = new SystemLocationDataSource();

Start the foreground service in the current application context with the following code:

MainPage.xaml.cs
Use dark colors for code blocksCopy
1
2
3
4
5
6
var intent = new Android.Content.Intent(Android.App.Application.Context, typeof(LocationService));

// Foreground Services are only supported and required after Android version Oreo (API level 26).
// Foreground service is required to keep the service running in the background when the main app is not in the foreground.
// Start the service as a foreground service.
_ = Android.App.Application.Context.StartForegroundService(intent);

Ensure the following permissions and service declaration exist in the AndroidManifest.xml file:

AndroidManifest.xml
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<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" />
<application>
    <service android:name=".LocationService" android:foregroundServiceType="location" />
</application>

iOS

If you need background location updates in your iOS app, you can update your project to add the background mode capability.

Ensure the following code is added to the MainPage.xaml.cs file to create the SystemLocationDataSource and to request background location updates:

MainPage.xaml.cs
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
_locationDataSource = new SystemLocationDataSource
{
    // Set AllowsBackgroundLocationUpdates to true to allow location updates when the app is in the background.
    AllowsBackgroundLocationUpdates = true,

    // Set ActivityType which is used to determine when location updates should be delivered.
    // This is used to help determine when to turn off GPS hardware to save power.
    // For more information on different activity types, refer to Apple's documentation:
    // https://developer.apple.com/documentation/corelocation/clactivitytype
    ActivityType = CoreLocation.CLActivityType.Other,
};

Add location usage descriptions and background modes to the Info.plist file:

Info.plist
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app requires background location updates for tracking your position.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.