【问题标题】:Getting location in xamarin forms in the background在后台以 xamarin 形式获取位置
【发布时间】:2019-11-16 20:08:36
【问题描述】:

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

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

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

【问题讨论】:

  • 我以前从来没有这样做过。但我想,创建一个粘性服务并轮询位置服务会为你解决问题。看看github.com/shinyorg/shiny。这个库有很多你可能需要的东西。
  • 您可以使用GeolocatorPlugin和阅读this document了解Android中的服务。

标签: android xamarin.forms location


【解决方案1】:

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

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    相关资源
    最近更新 更多