Here is a step by step tutorial about adding a sample BackgroundTask to your solution. The presented procedure is the same for: Windows Phone 8.1 Silverlight, Runtime and Windows Universal Apps.

What are Background Tasks and what is their usage:

If you app is not running actively and is not currently visible on screen , Windows OS will suspend it. So to overcome this problem winRT libraries introduces classes known as background tasks.

There are few conditions in which you can use these tasks and are listed below:

  1. Internet Availability/Unavailability
  2. Session Connected/Disconnected
  3. User Present/Not Present

Background tasks are a kind of thread that runs without making your application active.

If you want to stream an audio , update tiles , integrate lock screen notifications or want to give push/toast notifications then background tasks can help you.

Implementation

  1. Fisrt we have to add a new RuntimeComponent to our solution. To do this, right click on your solution in Solution explorer window in Visual Studio. Then click Add, New project… and choose Windows Runtime Component (Pic. 1) – depending on your purpose it can be portable or windows phone.
    adding background tasks
  2. Adding background tasksOnce we have the new project added, we need to add a reference (Pic. 2) to it in our main project in which we will register our BackgroundTask – without this step, our App will crash once we try to run the background code.
  3. Here comes the time to define our BackgroundTask. Of course the purpose of it depends on our needs. Let our task inform the User that it is running – for this we will implement a Toast message. We shall also remember that to make it work we need to set our App as Toast capable – open Package.appxmanifest file, chose Application tab, in section Notifications set App as toast capable. The simple code of our task can look like this:
    namespace MyTask
    {
    public sealed class FirstTask : IBackgroundTask
    {
    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 - Yeah"));
    textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!"));
    ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
    }
    }
    }
    

    What is imortant in the code above:

    We need to define a sealed class that will implement IBackgroundTask interface – which means that we will have to write a public void Run(IBackgroundTaskInstance taskInstance) method, that will perform our background work.
    the name of the class and the namespace are imortant as we will have to specify the entry point of our BackgroundTask (see next step)
    our Run method can be asynchronous, in this case we will have to obtain a BackgroundTaskDeferral by using a taskInstance.GetDeferral() method. This will inform the OS that our background task might continue to perform work after the Run method returns. We must only remember to call BackgroundTaskDeferral.Complete() once we finish our job.

  4. Now is the time to declare the entry point of our background task. To do this we need to open Package.appxmanifest file, find Declarations tab, choose BackgroundTask in dropdown menu and click Add. We should see it defined in the list below. We must also decide the type of our BackgroundTask – if it will be invoked upon System event, Timer or other. For the purpose of this example we will use Timer type – our task will be fired upon TimeTrigger event. All this you can see in the picture 3.
    Declaring background tasks
  5. The time has come to register our BackgroundTask. First we shall check if the task is already registered, to do this we can enumerate BackgroundTaskRegistration.AllTasks , for the sake of simplicity, once we have found our task, we will just return from the method. To register the task we will use BackgroundTaskBuilder – we will need to specify its entry point (the same as we had set in Declarations), provide a name of the task, set the Trigger (that will fire our task) and optionally we can specify SystemCondition. The sample code can look like this:
    private async void RegisterBtn_Click(object sender, RoutedEventArgs e)
    {
    string myTaskName = "FirstTask";
    
    // check if task is already registered
    foreach (var cur in BackgroundTaskRegistration.AllTasks)
    if (cur.Value.Name == myTaskName)
    {
    await (new MessageDialog("Task already registered")).ShowAsync();
    return;
    }
    
    // Windows Phone app must call this to use trigger types (see MSDN)
    await BackgroundExecutionManager.RequestAccessAsync();
    
    // register a new task
    BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "MyTask.FirstTask" };
    taskBuilder.SetTrigger(new TimeTrigger(15, true));
    BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
    
    await (new MessageDialog("Task registered")).ShowAsync();
    }
    

    In the code above, we have registered a task that will be fired upon TimeTrigger event. Althought we have set its freshness time to 15 minutes, it doesn’t mean that it will be fired exacly after this time – OS has a build-in timer that runs background tasks in 30 minutes intervals on Windows Phone (15 minutes on Windows). We have also set the task as OneShot, which means that it will be fired once (not in 15-30 minute intervals).

    Finally once we click the button (invoke the method), our BackgroundTask will be registered and it should be run after 15-30 minutes. But what to do to test it faster – do we, as developers, have to wait? No, there is quite an easy way to invoke the BackgroundTask earlier, upon demand. To do this we have to open the Debug location toolbar in Visual Studio, select our task from dropdown menu Lifecycle events (sometimes you may need to open the menu few times to refresh it) and once we click on the name it will be fired (Pic. 4).

    Background Tasks

 

That’s All

Happy Coding.