private void Button_Click(object sender, RoutedEventArgs e)
{
if (taskAdvertisementWatcher != null)
{
taskAdvertisementWatcher.Completed -= OnBackgroundTaskCompleted;
taskAdvertisementWatcher.Unregister(true);
taskAdvertisementWatcher = null;
btnRegisterUnregister.Content = "Register Background Task";
}
else
{
//Register the new task
// Applications registering for background trigger must request for permission.
BackgroundExecutionManager.RequestAccessAsync().AsTask().ContinueWith(async (r) =>
{
if (r.IsFaulted || r.IsCanceled)
return;
if ((r.Result == BackgroundAccessStatus.Denied) || (r.Result == BackgroundAccessStatus.Unspecified))
{
await new MessageDialog("Not able to run in background. Application must given permission to be added to lock screen.").ShowAsync();
Application.Current.Exit();
}
// Create and initialize a new trigger to configure it.
trigger = new BluetoothLEAdvertisementWatcherTrigger();
// Add the manufacturer data to the advertisement filter on the trigger:
trigger.AdvertisementFilter.Advertisement.iBeaconSetAdvertisement(new iBeaconData());
// By default, the sampling interval is set to be disabled, or the maximum sampling interval supported.
// The sampling interval set to MaxSamplingInterval indicates that the event will only trigger once after it comes into range.
// Here, set the sampling period to 1 second, which is the minimum supported for background.
trigger.SignalStrengthFilter.SamplingInterval = TimeSpan.FromMilliseconds(1000);
// At this point we assume we haven't found any existing tasks matching the one we want to register
// First, configure the task entry point, trigger and name
var builder = new BackgroundTaskBuilder();
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
builder.Name = taskName;
// Now perform the registration. The registration can throw an exception if the current
// hardware does not support background advertisement offloading
try
{
taskAdvertisementWatcher = builder.Register();
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
// For this scenario, attach an event handler to display the result processed from the background task
taskAdvertisementWatcher.Completed += OnBackgroundTaskCompleted;
btnRegisterUnregister.Content = "Unregister Background Task";
});
}
catch (Exception ex)
{
taskAdvertisementWatcher = null;
switch ((uint)ex.HResult)
{
case (0x80070032): // ERROR_NOT_SUPPORTED
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await new MessageDialog("The hardware does not support background advertisement offload.").ShowAsync();
Application.Current.Exit();
});
break;
default:
throw ex;
}
}
});
}
}
}