public async void Run(Windows.ApplicationModel.Background.IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral deferral = taskInstance.GetDeferral(); try { DeviceConnectionChangeTriggerDetails details = (DeviceConnectionChangeTriggerDetails)taskInstance.TriggerDetails; BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(details.DeviceId); SmartPack device = new SmartPack(bleDevice); if (bleDevice.ConnectionStatus == BluetoothConnectionStatus.Connected) { if (device.AlertOnDevice && device.HasLinkLossService) { await device.SetAlertLevelCharacteristic(); } } else { if (device.AlertOnPhone) { XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01); xml.SelectSingleNode("/toast/visual/binding/text").InnerText = string.Format("Device {0} is out of range.", device.Name); ToastNotification toast = new ToastNotification(xml); ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier(); notifier.Show(toast); } } } finally { deferral.Complete(); } }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { // Request the right to have background tasks run in the future. This need only be done once // after the app is installed, but it is harmless to do it every time the app is launched. if (await BackgroundExecutiondManager.RequestAccessAsync() == BackgroundAccessStatus.Denied) { // TODO: What? } // Acquire the set of background tasks that we already have registered. Store them into a dictionary, keyed // by task name. (For each LE device, we will use a task name that is derived from its Bluetooth address). Dictionary <string, BackgroundTaskRegistration> taskRegistrations = new Dictionary <string, BackgroundTaskRegistration>(); foreach (BackgroundTaskRegistration reg in BackgroundTaskRegistration.AllTasks.Values) { taskRegistrations[reg.Name] = reg; } // Get the list of paired Bluetooth LE devicdes, and add them to our 'devices' list. Associate each device with // its pre-existing registration if any, and remove that registration from our dictionary. Devices.Clear(); foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); Racer device = new Racer(bleDevice); if (taskRegistrations.ContainsKey(device.TaskName)) { device.TaskRegistration = taskRegistrations[device.TaskName]; taskRegistrations.Remove(device.TaskName); } Devices.Add(device); } // Unregister any remaining background tasks that remain in our dictionary. These are tasks that we registered // for Bluetooth LE devices that have since been unpaired. foreach (BackgroundTaskRegistration reg in taskRegistrations.Values) { reg.Unregister(false); } }