在后台以xamarin形式获取位置

问题描述 投票:1回答:1

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

我在应用程序处于前台时使用了LocationCallback,这似乎可以正常工作,但是我想知道是否只是不时地醒来并查看GetLastLocationAsync还是仅在某些主动请求时才更新该信息?地点信息。

实现后台服务的最佳方法是什么,该后台服务将把设备位置馈送到端点,而不管应用程序是否在前台?

android xamarin.forms location
1个回答
0
投票

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

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;
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.