简体   繁体   中英

Getting location in xamarin forms in the background

I'm attempting to create a xamarin forms application which will get location updates and feed them to an HTTP endpoint. I'm having a great deal of difficulty understanding how to go about running a service in the background so that I continue to receive location information regardless of if the application is open or not especially in face of the change in API level 26 https://developer.android.com/about/versions/oreo/background.html .

I was using a LocationCallback when the application was in the foreground and that seemed to work okay but I'm wondering if just waking up from time to time and looking at GetLastLocationAsync or if that information is only updated when something actively requests location information.

What's the best way to implement a background service which will feed device location to an endpoint regardless of if the application is in the foreground?

I achieved it by registering another service and subscribed to location updates from within it.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM