我想实现一个应用程序,可以连续将设备位置发送到Web服务。在文档中查找后,我找到了Geolocation类和一些关于位置跟踪的文章:
通过实现这两篇文章中讨论的示例项目,我注意到geolocator_PositionChanged()事件并没有在每个位置更新时触发。在两次执行事件之间存在延迟(约10/15分钟)。奇怪的是,即使应用程序在前台执行(而不仅仅是在后台),这种情况也会发生。我正在使用Windows Phone模拟器。
在我的应用程序中,我有一个地图控件,需要显示用户的位置,因此我需要确保geolocator_PositionChanged()事件对于每个位置更新都能正确触发,而且没有延迟。
1)如何使用Geolocator类跟踪(无延迟)设备的位置?
在网络上搜索后,我找到了GeoCoordinateWatcher类,可以提供设备的持续位置跟踪。以下是代码:
public MainPage()
{
InitializeComponent();
this.GetCoordinate();
}
private void GetCoordinate()
{
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 1
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.Start();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
//Get position data
var pos = e.Position.Location;
//Update mypos object
mypos.update(pos.Latitude, pos.Longitude);
//Update data on the main interface
MainMap.SetView(mypos.getCoordinate(), MainMap.ZoomLevel, MapAnimationKind.Parabolic);
}
它有效:watcher_PositionChanged()事件会立即触发,没有延迟。
2)为什么GeoCoordinateWatcher没有延迟?GeoCoordinateWatcher类和Geolocator类有什么区别?
最后,应用程序应该在不活动时将设备位置发送到Web服务。因此,我需要一个后台任务。正如Romasz在这里提出的那样,我可以使用带有某些限制的Geolocator类。
3)我可以在后台使用GeoCoordinateWhatcher吗?如果可以,怎么做?
我的目标是实现一个无延迟的位置跟踪应用程序,甚至可以在后台工作。该应用程序应该跟踪设备的位置并持续更新Web服务(即使在后台)。我该如何做?什么是最佳方法?我了解Windows Phone应用程序生命周期,并可以接受一些后台执行的限制。后台执行的限制是什么?