侦听后台的地理围栏事件 (HTML)
[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]
本主题将指导你在应用中逐步设置后台任务以侦听 Geofence 通知。
路线图: 本主题与其他主题有何关联?请参阅:
简介
在创建地理围栏后,你需要添加逻辑,以便处理当出现地理围栏事件时所发生的情况。 按照你设置的 MonitoredStates,你可能会在下列情况中收到事件:
- 用户进入了关注的区域。
- 用户离开了关注的区域。
- 地理围栏过期或者已被删除。请注意,删除事件并不能激活后台应用。
本主题描述了如何设置后台任务以便在发生地理围栏事件时通知你的应用。 不过,如果你的应用正在运行,则还可以通过应用来直接处理事件。 有关详细信息,请参阅处理前台的地理围栏通知和地理围栏指南。
侦听后台的地理围栏事件时需要执行较多的步骤:
- 在应用清单中声明后台任务。
- 在应用中注册后台任务。如果应用需要具备 Internet 访问权限以访问云服务,那么当此类事件被触发时,你可以为此设置一个标志。 你还可以设置一个标志以确保当事件被触发时用户在场,这样就可以保证用户收到通知。
- 如果应用在前台运行,则应提示用户授予应用位置权限。
为获取地理围栏状态更改事件而进行注册
在应用清单的“声明”选项卡下,为位置后台任务添加一个声明。执行此操作的步骤:
- 添加“后台任务”类型****的声明。
- 设置“位置”类型的属性任务。
- 在应用中设置一个入口点,以便在事件被触发时调用。
注册后台任务
下面的代码将注册地理围栏后台任务。请注意,在创建地理围栏时,我们已经检查了位置权限。 有关详细信息,请参考设置地理围栏。
function registerBackgroundTask() {
try {
// Request lockscreen access
Background.BackgroundExecutionManager.requestAccessAsync().done(
function (backgroundAccessStatus) {
var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
// Register the background task
builder.name = sampleBackgroundTaskName;
builder.taskEntryPoint = sampleBackgroundTaskEntryPoint;
builder.setTrigger(new Windows.ApplicationModel.Background.LocationTrigger(Windows.ApplicationModel.Background.LocationTriggerType.geofence));
// If it is important that there is user presence and/or
// internet connection when OnCompleted is called
// the following could be called before calling Register()
// var condition = new SystemCondition(SystemConditionType.userPresent | SystemConditionType.internetAvailable);
// builder.addCondition(condition);
geofenceTask = builder.register();
geofenceTask.addEventListener("completed", onCompleted);
LocationTriggerBackgroundTask.updateButtonStates(/*registered:*/ true);
switch (backgroundAccessStatus) {
case Background.BackgroundAccessStatus.unspecified:
case Background.BackgroundAccessStatus.denied:
WinJS.log && WinJS.log("This app is not allowed to run in the background.", "sample", "status");
break;
default:
// Finish by getting an initial position. This will present the location consent
// dialog if it's the first attempt for this application to access location.
getGeopositionAsync();
break;
}
},
function (e) {
// Did you forget to do the background task declaration in the package manifest?
WinJS.log && WinJS.log(e.toString(), "sample", "error");
}
);
} catch (ex) {
// HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED) === -2147024846
if (ex.number === -2147024846) {
WinJS.log && WinJS.log("Location Simulator not supported. Could not get permission to add application to the lock screen, this application must be added to the lock screen before the background task will run.", "sample", "status");
} else {
WinJS.log && WinJS.log(ex.toString(), "sample", "error");
}
}
}
相关主题
路线图
任务
参考
其他资源