我有一个侦听器,它每10秒或100米左右捕获一次位置。我正在使用
xam.plugin.geolocator
实现监听器。我的问题是,当我的应用程序最小化或打开了应用程序但手机被锁定时,位置侦听器无法正常工作(这意味着位置更改未捕获或保存在位置缓存中)。
这是我的代码:
async Task StartListening()
{
if (!CrossGeolocator.Current.IsListening)
{
var defaultgpsaccuracy = Convert.ToDouble(Preferences.Get("gpsaccuracy", String.Empty, "private_prefs"));
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(10), defaultgpsaccuracy, false, new Plugin.Geolocator.Abstractions.ListenerSettings
{
ActivityType = Plugin.Geolocator.Abstractions.ActivityType.Other,
AllowBackgroundUpdates = true,
DeferLocationUpdates = true,
DeferralDistanceMeters = 1,
DeferralTime = TimeSpan.FromSeconds(1),
ListenForSignificantChanges = true,
PauseLocationUpdatesAutomatically = false
});
}
}
我将此代码放在 login.xaml.cs
中应用程序的第一个视图/页面中这是我的问题:
答案 0 :(得分:0)
首先,您需要初始化StartListening,然后创建事件处理程序以进行位置更改和错误处理
public Position CurrentPosition { get; set; }
public event EventHandler PositionChanged;
不要忘记在构造函数中初始化它:
CurrentPosition = new Position();
await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(20), 10, true);
CrossGeolocator.Current.PositionChanged += PositionChanging;
CrossGeolocator.Current.PositionError += PositionError;
功能:
`private void PositionChanging(object sender, PositionEventArgs e)
{
CurrentPosition = e.Position;
if (PositionChanged != null)
{
PositionChanged(this, null);
}
}
private void PositionError(object sender, PositionErrorEventArgs e)
{
Debug.WriteLine(e.Error);
}`
您现在可以在需要任何最新职位时致电PositionChanged
别忘了停止收听:
`public async Task StopListeningAsync()
{
if (!CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= PositionChanging;
CrossGeolocator.Current.PositionError -= PositionError;
}`