我正在开发一个需要在定期时间内检测用户最后位置的应用程序。我使用了一些我在谷歌找到的教程,但没有一个工作,需要帮助。这是我的代码中的示例。
我在app.xaml.cs中创建了我的schdeuledactionservice。我已经在WMAppManifest.xml中添加了我的扩展任务。
来自WMAppManifest.xml
<ExtendedTask Name="BackgroundTask">
<BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="ToDoSchedulerAgent" Source="ToDoSchedulerAgent" Type="ToDoSchedulerAgent.TaskScheduler" />
</ExtendedTask>
调度程序代理:
public class TaskScheduler : ScheduledTaskAgent
{
public const string Name = "ToDoLocator";
public static Location location;
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
GeoCoordinateWatcher watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 10
};
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
watcher.Start();
}
NotifyComplete();
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
throw new NotImplementedException();
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
Deployment.Current.Dispatcher.BeginInvoke(() => PositionChanged(e));
}
void PositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
{
location = new Location();
location.Latitude = e.Position.Location.Latitude;
location.Longitude = e.Position.Location.Longitude;
}
}
答案 0 :(得分:2)
首先,不应在最终应用程序中使用“ScheduledActionService.LaunchForTest”,它仅用于测试。
其次,我使用这种方法,它工作正常 - 我启动GeoCoordinateWatcher并等待使用AutoResetEvent,直到它被初始化,然后我可以使用坐标:
private void WatcherStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
_status = e.Status;
switch (e.Status)
{
case GeoPositionStatus.Disabled:
case GeoPositionStatus.NoData:
case GeoPositionStatus.Ready:
_watcherLock.Set();
break;
case GeoPositionStatus.Initializing:
break;
default:
throw new ArgumentOutOfRangeException();
}
}
private readonly GeoCoordinateWatcher _watcher = new GeoCoordinateWatcher();
private readonly AutoResetEvent _watcherLock = new AutoResetEvent(false);
private GeoPositionStatus _status;
/// <summary>
/// Agent that runs a scheduled task
/// </summary>
protected override void OnInvoke(ScheduledTask scheduledTask)
{
_watcher.StatusChanged += WatcherStatusChanged;
_watcher.Start();
// wait until watcher is initialized
_watcherLock.WaitOne();
// if GPS is disabled or have no data, just return
if (_status == GeoPositionStatus.Disabled || _status == GeoPositionStatus.NoData)
{
NotifyComplete();
return;
}
// get current position
GeoCoordinate location = _watcher.Position.Location;
...
NotifyComplete();
}