Share via


Quickstart: Creating and registering a raw notification background task (XAML)

Note  Not using C#/VB/C++? See Quickstart: Creating and registering a raw notification background task (HTML).

 

You can create and register a background task function for your Windows Store app. This code then runs in response to the receipt of a raw notification, which gives your app functionality when it is not in the foreground.

To complete this procedure, you must edit three separate files: the app's code, the app's manifest, and a new file that contains the background task code.

Prerequisites

To understand this topic or to use the code it provides, you will need:

Instructions

1. Create the background task class

To run code in the background, you must create a class that implements the IBackgroundTask interface as shown in the following examples. This class runs when a raw notification is delivered.

To begin, create a new project in your app's solution. This project will contain your background task code. Import the Windows.ApplicationModel.Background namespace to the project. Add a code file to that project. In this case, we'll add a C# file named ExampleBackgroundTask.cs.

In the ExampleBackgroundTask.cs file, create a new class that implements the IBackgroundTask interface. That interface's Run method must be present in every background task as an entry point to be called when the specified event is triggered.

The following example shows a very basic starting point for the background task class. The body of your code, specific to your app-defined raw notification content, will replace the "// ..." comment.

using Windows.ApplicationModel.Background;
using Windows.Networking.PushNotifications;

namespace Tasks
{
    public sealed class ExampleBackgroundTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
            string content = notification.Content;

            // ...
        }        
    }
}

If you run any asynchronous code in your background task, then your background task needs to use a deferral. Without a deferral, the background task process can terminate unexpectedly if the Run method completes before your asynchronous method.

Request the deferral in the Run method before you call the asynchronous method. Save the deferral in a global variable so that it can be accessed from the asynchronous method. Declare the deferral complete after the asynchronous code has completed. The following code demonstrates those steps by using an asynchronous method named ExampleMethodAsync. The comments "// ..." will be replaced with your code that performs work in the background.

Note  In C#, your background task's asynchronous methods can be called using the "async" or "await" keywords. In C++, a similar result can be achieved by using a task chain.

 

For more information on asynchronous patterns in Windows Store apps, see Asynchronous programming. For additional examples of the use of deferrals to prevent a background task from terminating before it should, see the background task sample.

public async void Run(IBackgroundTaskInstance taskInstance)
{
    BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
    
    RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
    string content = notification.Content;

    // ...

    // Insert code to start one or more asynchronous methods using the "await" keyword.
    var result = await ExampleMethodAsync();
    
    // ...
    
    _deferral.Complete();
}

2. Declare the background task in your app's manifest

Note  As a prerequisite to this step, your app must choose a lock screen option and provide a badge logo before background tasks are supported. For more information, see Quickstart: Showing tile and badge updates on the lock screen.

 

Before your app can register a background task, you must declare the background task and its trigger in the app's manifest. This can be done directly as XML or through the Microsoft Visual Studio manifest editor.

  • To use the Manifest Editor, double-click your app's Package.appxmanifest file in Visual Studio. On the Declarations tab, choose Background Tasks from the Available Declarations drop-down list. As a trigger, choose Push notification under Properties. In the Start page box, enter the name of the background task's file, in our case ExampleBackgroundTask.cs.

    If your app uses more than one background task, repeat this step for each task, pointing each time to a different file.

  • To add the information directly to the manifest's XML, open the manifest in a text editor. In the Extensions element, add an Extension element for the background task class. The Category attribute should be set to "windows.backgroundTasks" and the StartPage attribute should name the background task's file, in our case ExampleBackgroundTask.cs.

    If your app uses more than one background task, add a separate Extension element for each task, each element pointing to a different file.

    You must list each type of trigger that a background task uses. Because we're creating a background task that triggers in response to a raw notification, we will declare a push notification trigger. Add a BackgroundTasks element to the Extension element, with its Task element set to "pushNotification".

    The complete Extension element is shown here.

<Extension Category="windows.backgroundTasks" StartPage="js\examplebackgroundtask.js">
  <BackgroundTasks>
    <Task Type="pushNotification"/>
  </BackgroundTasks>
</Extension>

3. Register your background task in your app

The following examples provide code that you will add to your app (for instance, in its MainPage.xaml.cs file) to register your background task as a response to a raw notification.

Note  You can also create a function dedicated to registering background tasks. For more information, see How to register a background task. In that case, instead of using these next steps, you can simply construct the trigger and provide it to the registration function along with the task name, task entry point, and (optionally) a condition.

 

First, determine whether the background task is already registered. This step is important. If your app doesn't check for an existing background task registration, it could register the same task more than once. This could cause performance issues and CPU usage that could prevent the task from completing.

This example iterates through the Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks property and sets a flag to true if the task is already registered.

var taskRegistered = false;
var exampleTaskName = "ExampleBackgroundTask";

var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks.first();

while (iter.hasCurrent) {
    var task = iter.current.value;
    
    if (task.name == exampleTaskName) {
        taskRegistered = true;
        break;
    }

    iter.moveNext();
}

If your app finds that the background task is not registered, it can register it by calling the Windows.ApplicationModel.Background.BackgroundTaskBuilder.Register method. In the call to this method, you include the task's entry point, which is the name of your background task class, prefixed with the namespace.

The background task trigger controls when the background task runs. In this case, by using a PushNotificationTrigger, it is triggered when a raw notification is delivered to the push notification channel.

if (!taskRegistered) {

var builder = new BackgroundTaskBuilder();

builder.Name = exampleTaskName;
builder.TaskEntryPoint = "Task.ExampleBackgroundTask";
builder.SetTrigger(new Windows.ApplicationModel.Background.PushNotificationTrigger());
BackgroundTaskRegistration task = builder.Register();
}

Summary

You should now understand the basics of writing a background task class for use with raw notifications, including how to register the background task from within your app. You should also understand how to update the app manifest so that Windows allows your app to register its background tasks.

Note  You can download the background task sample to see these code examples and more, in the context of a complete and robust Windows Store app that uses several different types of background tasks.

 

Raw notifications sample

Raw notification overview

Guidelines and checklist for raw notifications

Quickstart: Intercepting push notifications for running apps

RawNotification