簡體   English   中英

在后台獲取 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;
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM