How to write a background task for raw push notifications (XAML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

This topic shows how to write a background task to receive background network notifications that use raw push notifications in a Windows Store app.

What you need to know

Technologies

Prerequisites

  • The following information applies to any connected or network-aware Windows Store app that depends on network connections using raw push notifications to always be connected. This topic applies to apps written in C++/XAML and apps using the .NET Framework 4.5 in C#, VB.NET, or managed C++ on Windows 8 and Windows Server 2012.

    Background network connectivity using raw push notifications is supported by a JavaScript app. For more information on background tasks that apply to JavaScript apps, see Supporting your app with background tasks. For information on background network connectivity supported by a JavaScript app, see Staying connected in the background (HTML).

Instructions

Step 1: Writing your background task

An important next step in making the app always reachable is to provide the app code that runs when a raw push notification occurs. For example, in the case of an email app that uses incoming raw push notifications to signal that new mail has arrived on the server, the app needs to run code to process the data in the raw push notification. This data might contain a list of new emails received to raise a notification to the user. An app might also schedule to connect to the email server and download the new emails from the server the next time the app is not longer suspended. This processing is done in the background task.

Every background task is implemented in its Run method, which is part of the IBackgroundTask interface. The Run method is part of the class that was created when an app registered for a raw push notification. This was specified as part of the BackgroundTaskBuilder.TaskEntryPoint in the app manifest.

The following sample show a Run method implemented as part of the class that uses raw push notifications.

using System.Diagnostics;
using Windows.ApplicationModel.Background;
using Windows.Networking.PushNotifications;
using Windows.Storage;

namespace BackgroundTasks
{
    // You must use a sealed class, and make sure the output is a WINMD.
    public sealed class SampleBackgroundTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get the background task details
            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
            string taskName = taskInstance.Task.Name;

            Debug.WriteLine("Background " + taskName + " starting...");

            // Store the content received from the notification so it can be retrieved from the UI.
            RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
            settings.Values[taskName] = notification.Content;

            Debug.WriteLine("Background " + taskName + " completed!");
        }
    }
}
using namespace BackgroundTasks;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Networking::PushNotifications;
using namespace Windows::Storage;

void SampleBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
{
    // Get the background task details
    auto settings = ApplicationData::Current->LocalSettings;
    auto taskName = taskInstance->Task->Name;

    // Store the content received from the notification so it can be retrieved from the UI
    auto notificationDetails = dynamic_cast<IRawNotification^>(taskInstance->TriggerDetails);
    settings->Values->Insert(taskName, notificationDetails->Content);
}
Imports System.Diagnostics
Imports Windows.ApplicationModel.Background
Imports Windows.Networking.PushNotifications
Imports Windows.Storage

' You must use a sealed class, and make sure the output is a WINMD.
Public NotInheritable Class SampleBackgroundTask
    Implements Windows.ApplicationModel.Background.IBackgroundTask

    Public Sub Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run
        ' Get the background task details
        Dim settings As ApplicationDataContainer = ApplicationData.Current.LocalSettings
        Dim taskName As String = taskInstance.Task.Name

        Debug.WriteLine("Background " & taskName & " starting...")

        ' Store the content received from the notification so it can be retrieved from the UI.
        Dim notification As RawNotification = DirectCast(taskInstance.TriggerDetails, RawNotification)
        settings.Values(taskName) = notification.Content

        Debug.WriteLine("Background " & taskName & " completed!")
    End Sub

End Class

Note You cannot reference elements of your app user interface (UI) in a background task because the UI elements in your app are not running. When your code is executing in the background task, you can receive the raw push notification payload, process the information, and raise a notification to the user.

The lifetime of the background task is controlled by the Run method. If an app exits the Run method, the app is suspended.

When an app background task is triggered, the operating system ensures that appropriate synchronization delivers the raw push notification data to the app or returns an error (connection aborted, for example). Similarly, at the end of the background task an app must ensure that any pending data is sent before the app is suspended.

When the background task triggers you will want to identify the corresponding raw push notification channel from the trigger details and interpret the content data received.

Although the background task is primarily targeted towards an app in the suspended state, an app configured with background tasks will also have these background tasks trigger when the app is in the foreground.

Step 2: Previous steps

For more information on how to create a lock screen app to receive background network notifications that use raw push notifications, see Quickstart: Create a lock screen app that uses background raw push notifications.

For more information on the process of registering a push notification channel and send it to your server, register a background task to activate from a raw push notification, and send a raw push notification to the channel and activate the background task, see How to use WNS to deliver raw push notifications to a lock screen app.

Step 3: Further steps

For more information on guidelines and checklists for using raw push notifications, see Guidelines and checklist for raw notifications.

Other resources

Adding support for networking

Background Networking

How to use WNS to deliver raw push notifications to a lock screen app

Lock screen overview

Push notification overview

How to create a lock screen app that uses background raw push notifications

Staying connected in the background

Supporting your app with background tasks

Troubleshooting and debugging network connections

Reference

HttpClient

HttpClientHandler

IXMLHTTPRequest2

System.Net.Http

Windows.ApplicationModel.Background

Windows.Networking.BackgroundTransfer

Windows.Networking.PushNotifications

Windows.Networking.Sockets

Windows.Web.Http

Samples

Background task sample

Lock screen apps sample

Push and periodic notifications client-side sample

Raw notifications sample