6

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?

Romasz
  • 29,662
  • 13
  • 79
  • 154
Fela Ameghino
  • 224
  • 4
  • 11

1 Answers1

22

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):

    1. BackgroungTask must be a Windows Runtime Componenet (no matter if your App is Runtime or Silverlight). To add a new one, right click on your Solution in Solution Explorer window in VS, select Add then New project and choose Windows Runtime Component.

    winRTcomponent

    2. Add a reference in your main project.

    addreference

    3. Specify Declarations in Package.appxmanifest file - you need to add a Backgorund Task, mark Timer and specify Entry Point for the Task. The Entry Point will be a Namespace.yourTaskClass (which implements IBackgroundTask) - the added Windows Runtime Component.

    declaration

    4. How can your BackgroundTask look like? - let's say we want to send a Toast from it (of course it can be many other things):
    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));
          }
       }
     }
    

    5. Finally, let's register our BackgroundTask in main project:
    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).

run faster

Here you can download my sample code - WP8.1 Silverlight App.

Romasz
  • 29,662
  • 13
  • 79
  • 154
  • Thank you for the reply, but I've already tried that and the same code in RT works and in Silverlight makes the app crash when the task is triggered (And it is not executed) – Fela Ameghino Jun 06 '14 at 07:51
  • @FelaAmeghino Have you followed the steps? I've added a [sample code](http://1drv.ms/1jYOnzZ) - maybe it will help. – Romasz Jun 06 '14 at 08:06
  • 1
    Tried now, and it works, dunno, I will retry on main project (I tried last night, I was very sleepy :P), thank you :) – Fela Ameghino Jun 06 '14 at 08:10
  • 1
    Excellent answer, love the pics. – D.Rosado Jun 25 '15 at 13:08
  • @Romasz Useful post, but one question apart from this topic. How to handle cancelled background task? If app is allowed to stop in Battery Saver in Windows Phone 8.1. I need to detect when background task is cancelled so that I would invoke another function. Already I have gone through and implemented background task in my project, https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977052.aspx?f=255&MSPPError=-2147217396 Still I couldn't detect whether background task is cancelled or not? Could you help me.? – Balasubramani M Jul 25 '15 at 15:20
  • @BalasubramaniM I think you should be able to erform some code in [OnCanceled](https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.applicationmodel.background.backgroundtaskcanceledeventhandler.aspx) event. – Romasz Jul 27 '15 at 04:42
  • @Romasz Yes I have added. But OnCanceled method is not invoking. Thats what my problem is. – Balasubramani M Jul 28 '15 at 17:50
  • @Romasz I am cancelling the task in Battery Saver. I think this is the right way to cancel right? Do you have any other way to cancel? – Balasubramani M Aug 01 '15 at 11:03
  • @BalasubramaniM The best place would be to just cancel it from the app that registered the BTask. – Romasz Aug 01 '15 at 16:57
  • @Romasz Do we expect user to cancel background task only from app? How could we cancel from app? Any code? – Balasubramani M Aug 01 '15 at 19:44
  • @BalasubramaniM I think you fetch all your tasks with [AllTasks](https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977050.aspx), then call [Unregister with Cancel option](https://msdn.microsoft.com/en-us/library/windows/apps/br229870). Of course task can also be cancelled by OS or in other cases. Also please don't try to ask so many questions in comments. – Romasz Aug 01 '15 at 19:57
  • @Romasz Am not using AllTasks anything, It's Ok. Thank you for your response. Still I didn't get proper answer for my solution. – Balasubramani M Aug 02 '15 at 13:27
  • @Romasz I have your code running (Thanks its awesome to so quick have the backgroundTask). I have a silverlight app where I want to communicate with Azure from the backgroundtask, but when I add the Nuget package, I cannot compile the system suddenly I get errors all over. I think its because the two projects would reference two different versions of azure, i.e. winrt and silverlight. Do you have any experience with this? I am thinking of opening a question, but simply cannot get the stuff working properly, and the errors are not that descriptive. – JTIM May 18 '16 at 06:44
  • @JTIM Unfortunately I don't have experience in this yet. And if you have package only in one project (wrt/app) then it works ok? – Romasz May 18 '16 at 06:51
  • @Romasz yes it seems like it ! In my `app.xaml.cs` in the startup project I have my connection string to azure. Everything works. After installing nuget package in `BackgroundTask` the connection string gets an error that refers to issues with the project references, and nothing has been changed in other than the `BackgroundTask`s Package. Okay, it was worth a try i'll look at it and probably end with a question, cause all yesterday I tried finding solutions :/ – JTIM May 18 '16 at 06:54