在前景處理地理柵欄通知 (HTML)
[ 本文的目標對象是撰寫 Windows 執行階段 App 的 Windows 8.x 和 Windows Phone 8.x 開發人員。如果您正在開發適用於 Windows 10 的 App,請參閱 最新文件 ]
本主題將逐步引導您完成在應用程式的前景處理 Geofence 通知的步驟。
藍圖: 這個主題與其他主題的相關性?請參閱:
簡介
一旦建立您的地理柵欄之後,就必須加入邏輯,以處理發生地理柵欄事件時所發生的情況。 根據您已經設定的 MonitoredStates,您可能會在下列情況下收到某個事件:
- 使用者進入相關的區域時。
- 使用者離開相關的區域時。
- 地理柵欄過期或遭到移除時。請注意,系統不會啟動移除事件的背景應用程式。
您可以在應用程式執行時,直接從應用程式接聽事件,或登錄背景工作,讓您可以在事件發生時,收到背景通知。如需有關背景工作和地理柵欄的詳細資訊,請參閱在背景接聽地理柵欄事件、從背景工作處理地理柵欄通知,以及地理柵欄的指導方針。
登錄地理柵欄狀態變更事件
若要讓您的應用程式收到地理柵欄狀態變更的前景通知,您必須登錄事件處理常式。 這通常會在建立地理柵欄時設定。
function initialize() {
// other initialization logic
Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.current.addEventListener("geofencestatechanged", onGeofenceStateChanged);
}
實作地理柵欄事件處理常式
下一步是實作事件處理常式。 此處所採取的動作將取決於您的應用程式使用地理柵欄的用途。
public async void OnGeofenceStateChanged(GeofenceMonitor sender, object e)
{
var reports = sender.ReadReports();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
foreach (GeofenceStateChangeReport report in reports)
{
GeofenceState state = report.NewState;
Geofence geofence = report.Geofence;
if (state == GeofenceState.Removed)
{
// remove the geofence from the geofences collection
GeofenceMonitor.Current.Geofences.Remove(geofence);
}
else if (state == GeofenceState.Entered)
{
// Your app takes action based on the entered event
// NOTE: You might want to write your app to take particular
// action based on whether the app has internet connectivity.
}
else if (state == GeofenceState.Exited)
{
// Your app takes action based on the exited event
// NOTE: You might want to write your app to take particular
// action based on whether the app has internet connectivity.
}
}
});
}
相關主題
藍圖
工作
參考
其他資源