![](/img/trans.png)
[英]Xamarin Forms Android Pie Not Getting Current Location in App Background Sleep Mode
[英]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.