地理围栏是LBS的一种新应用,就是用一个虚拟的栅栏围出一个虚拟地理边界。当手机进入、离开某个特定地理区域,或在该区域内活动时, 手机可以接收自动通知和警告。有了地理围栏技术,位置社交网站就可以帮助用户在进入某一地区时自动登记。Windows Phone提供了API直接支持地理围栏的编程,而不需要开发者去自定义实现这样的业务封装。
地理围栏类:Geofence
Geofence具有下面的一些重要的属性,用于定义地理围栏的值:
(1)string Id:用于识别地理围栏的 Id。
(2)IGeoshape Geoshape:圆形关注区域,表示围栏的区域。
(3)MonitoredGeofenceStates MonitoredStates:指明需要为哪些地理围栏事件接收通知 - 输入定义的区域、保留定义的区域或者删除地理围栏。。
(4)bool SingleUse:当满足了监视地理围栏的所有状态时,是否将删除地理围栏。
(5)TimeSpan DwellTime:指明在触发进入/退出事件之前,用户必须位于所定义区域之内/之外的时间。
(6)DateTimeOffset StartTime:指明何时开始监视地理围栏。
(7)TimeSpan Duration:监视地理围栏的时间。
在创建地理围栏后,你需要添加逻辑,以便处理当出现地理围栏事件时所发生的情况。 按照你设置的 MonitoredStates,你可能会在下列情况中收到事件:
(1)用户进入了关注的区域。
(2)用户离开了关注的区域。
(3)地理围栏过期或者已被删除。请注意,删除事件并不能激活后台应用。
判断当前地理围栏是否存在:
foreach(var geo in GeofenceMonitor.Current.Geofences)
{
if(geo.Id==fenceKey)
{
await new MessageDialog("该地理围栏已经添加").ShowAsync();
return;
}
}
初始化:
我们可以通过4个构造方法来构造一个地理围栏的对象,分别如下所示:
public Geofence(string id, IGeoshape geoshape);
public Geofence(string id, IGeoshape geoshape, MonitoredGeofenceStates monitoredStates, bool singleUse);
public Geofence(string id, IGeoshape geoshape, MonitoredGeofenceStates monitoredStates, bool singleUse, TimeSpan dwellTime);
public Geofence(string id, IGeoshape geoshape, MonitoredGeofenceStates monitoredStates, bool singleUse, TimeSpan dwellTime, DateTimeOffset startTime, TimeSpan duration);
添加地理围栏监控:
构造好维拉对象之后,把Geofence对象添加到地理围栏的监控中设置地理围栏,示例代码如下所示:
GeofenceMonitor.Current.Geofences.Add(geofence);
处理地理围栏状态改变事件:
// 给GeofenceMonitor对象添加地理围栏状态改变事件
GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
// 地理围栏状态改变事件
public async void OnGeofenceStateChanged(GeofenceMonitor sender, object e)
{
// 读取状态改变的报告
var reports = sender.ReadReports();
// 启动UI线程
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
foreach (GeofenceStateChangeReport report in reports)
{
// 地理围栏的状态
GeofenceState state = report.NewState;
// 地理围栏对象
Geofence geofence = report.Geofence;
if (state == GeofenceState.Removed)
{
// 地理围栏已被移除
}
else if (state == GeofenceState.Entered)
{
// 用户进入了地理围栏区域
}
else if (state == GeofenceState.Exited)
{
// 用户退出地理围栏区域
}
}
});
}