Continuous location update in .NET MAUI

Viewed 39

I've built a simple MAUI test app that reads the location every 3 seconds and writes it to a label control. When testing in Android (both on emulator and device) I can see the Android location icon appearing and disappearing each time a location is being read.

When using other tracking apps for reference, the location icon is always on, so I guess there is some way to keep the connection to the GPS open while the app is running. Is this possible in MAUI?

CancellationTokenSource tokenSource;
CancellationToken token;

private async void OnStartClicked(object sender, EventArgs e)
{
    tokenSource = new();
    token = tokenSource.Token;
    
    PermissionStatus permissionStatus = await Permissions.RequestAsync<Permissions.LocationAlways>();

    if (permissionStatus == PermissionStatus.Granted)
    {
        Task locationTask = Task.Run(() => UpdateLocation(token), token);
    }
}

private async Task UpdateLocation(CancellationToken ct)
{
    while (true)
    {
        if (ct.IsCancellationRequested)
        {
            viewModel.DebugText = $"distance cancel requested";
            return;
        }

        GeolocationRequest request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(5));
        CancellationTokenSource _cancelTokenSource = new CancellationTokenSource();
        Location location = await Geolocation.Default.GetLocationAsync(request, _cancelTokenSource.Token);

        while (location == null)
            Thread.Sleep(100);

        viewModel.LastLocation = location;

        await Task.Delay(3000);
    }
}
0 Answers
Related