在后台获取 xamarin 表单中的位置

Getting location in xamarin forms in the background

我正在尝试创建一个 xamarin 表单应用程序,它将获取位置更新并将它们提供给 HTTP 端点。我很难理解如何在后台处理 运行 一项服务,以便无论应用程序是否打开我都能继续接收位置信息,尤其是面对 API 26级https://developer.android.com/about/versions/oreo/background.html

当应用程序在前台时,我正在使用 LocationCallback,这似乎工作正常,但我想知道是否只是不时醒来并查看 GetLastLocationAsync,或者该信息是否只是当某些东西主动请求位置信息时更新。

实现后台服务的最佳方式是什么,无论应用程序是否在前台,该服务都会将设备位置提供给端点?

我通过注册另一项服务并从其中订阅位置更新来实现它。

using Xamarin.Essentials;

public class Service
{
    private IService service { get; }

    public Service(IService service)
    {
        this.service = service;
    }

    public async Task StartListening()
    {
        if (CrossGeolocator.Current.IsListening)
            return;

        await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(5), 10, true);

        CrossGeolocator.Current.PositionChanged += PositionChanged;
        CrossGeolocator.Current.PositionError += PositionError;
    }

    private void PositionChanged(object sender, PositionEventArgs e)
    {
        service.UpdateLocation(e.Position.Latitude, e.Position.Longitude);
    }

    private void PositionError(object sender, PositionErrorEventArgs e)
    {
        //Handle event here for errors
    }

    public async Task StopListening()
    {
        if (!CrossGeolocator.Current.IsListening)
            return;

        await CrossGeolocator.Current.StopListeningAsync();

        CrossGeolocator.Current.PositionChanged -= PositionChanged;
        CrossGeolocator.Current.PositionError -= PositionError;
    }
}

}