我想经常在App中保留手机的位置,因此我正在使用GetPositionAsync方法,并继续调用它。我已经写了一些代码,当我将其附加到一个简单的OnAppearing方法中时,一切工作正常。如果我在方法或while循环中编写它,那么当它到达GetPositionAsync或其他一些本地数据库时,我认为只有可以等待的方法,它才退出循环/方法。我正在使用异步。有什么想法吗?
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 20;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
location.Latitude = position.Latitude;
location.Longitude = position.Longitude;
await App.LocationDatabase.SaveLocationAsync(location);
await Task.Delay(TimeSpan.FromSeconds(10));
答案 0 :(得分:0)
您不共享任何循环代码,因此很难重现您的问题。
无论如何,您不应循环调用GetPositionAsync
,而应使用StartListeningAsync
方法并连接到PositionChange
事件。
async Task StartListeningAsync()
{
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)
{
//If updating the UI, ensure you invoke on main thread
var position = e.Position;
var output = "Full: Lat: " + position.Latitude + " Long: " + position.Longitude;
output += "\n" + $"Time: {position.Timestamp}";
output += "\n" + $"Heading: {position.Heading}";
output += "\n" + $"Speed: {position.Speed}";
output += "\n" + $"Accuracy: {position.Accuracy}";
output += "\n" + $"Altitude: {position.Altitude}";
output += "\n" + $"Altitude Accuracy: {position.AltitudeAccuracy}";
Debug.WriteLine(output);
}
private void PositionError(object sender, PositionErrorEventArgs e)
{
Debug.WriteLine(e.Error);
//Handle event here for errors
}
async Task StopListeningAsync()
{
if(!CrossGeolocator.Current.IsListening)
return;
await CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= PositionChanged;
CrossGeolocator.Current.PositionError -= PositionError;
}
https://jamesmontemagno.github.io/GeolocatorPlugin/LocationChanges.html