I'm working on an app that uses BLE to communicate with an item and I need to receive background notifications from it. I am aware of the existence of GattCharacteristicNotificationTrigger
but I can't find any way to register a Background Task in a Silverlight 8.1 app.
Any tip?
Registering a BackgroundTask is quite well explained here at MSDN.
Here is simple example fired upon TimeTrigger and showing a Toast, the steps are (applies to both - RunTime and Silverlight apps):
Namespace.yourTaskClass
(which implements IBackgroundTask
) - the added Windows Runtime Component.
namespace myTask // the Namespace of my task
{
public sealed class FirstTask : IBackgroundTask // sealed - important
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// simple example with a Toast, to enable this go to manifest file
// and mark App as TastCapable - it won't work without this
// The Task will start but there will be no Toast.
ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList textElements = toastXml.GetElementsByTagName("text");
textElements[0].AppendChild(toastXml.CreateTextNode("My first Task"));
textElements[1].AppendChild(toastXml.CreateTextNode("I'm message from your background task!"));
ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Windows Phone app must call this to use trigger types (see MSDN)
await BackgroundExecutionManager.RequestAccessAsync();
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "myTask.FirstTask" };
taskBuilder.SetTrigger(new TimeTrigger(15, true));
BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
}
Compile, run and it should work. As you can see the task should start after 15 minutes (this time can vary as OS schedules task in specific intervals, so it will fire between 15-30 minutes). But how to debug a task faster?
There is a simple way - go to Debug location toolbar and you will see a dropdown Lifecycle events, choose your task from it and it will fire (sometimes open/close dropdown to refresh it).
Here you can download my sample code - WP8.1 Silverlight App.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With