Share via


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

This topic will show you how to use Windows Notification Service (WNS) and raw push notifications to receive network notifications in the background in a Windows Runtime app on the lock screen. This topic walks you through 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.

What you need to know

Technologies

Prerequisites

  • The following information applies to any connected or network-aware Windows Runtime app that depends on network connections using raw push notifications to always be connected. This topic applies to apps written in JavaScript on Windows 8.1, Windows Phone 8.1, and Windows Server 2012 R2.

    Background network connectivity using raw push notifications is supported by a JavaScript app and apps written in C++/XAML and apps using the .NET Framework 4.5 in C#, VB.NET, or managed C++. For more information on background networking tasks that apply to JavaScript apps, see Supporting your app with background tasks.

Instructions

Using WNS to deliver raw push notifications to a lock screen app

Apps that use WNS do not need to be running to receive push notifications and can appear to the user like they are running when they are not. For example, a weather app can always show the latest weather in an updated live tile. WNS can also be used to deliver on-screen notifications to users when important events happen. A good example of an on-screen notification is some breaking news event. Any device running Windows 8.1, Windows Phone 8.1, or Windows Server 2012 R2. with a connection to the Internet can use WNS. These WNS notifications usually are delivered as soon as they are sent.

Although WNS helps power the live tiles and notifications on the start screen of Windows 8.1, it can also be used to enable real-time connectivity scenarios such as IM, VoIP, and email. When an app that uses WNS is added to the lock screen, it can be used to activate a background task. A background task is part of your app code that runs when your app is in the background (no longer in the foreground).

Some examples of a background task that can be activated by a WNS notification include the following:

  • Call the notification badge API to increment a badge icon for an email app on the lock screen to indicate that a new email message has arrived.
  • Call the modification toast API to raise a notification for a VoIP app signaling an incoming phone call for the user.

There are four types of push notifications:

  • Tile update
  • Badge update
  • Toast notification
  • Raw notification

All Windows Runtime apps can use the first three push notifications when in the foreground. Only lock screen apps can receive raw push notifications from WNS. Raw notifications allow lock screen apps to run code in the form of a background task when the raw push notification arrives from WNS, even when the app is not in the foreground.

Most apps do not need to be a lock screen app and can use WNS without being on the lock screen. WNS can be used by all apps to update tiles and badges and to raise toast notifications when in the foreground. Using WNS with a lock screen app is a more advanced version of using WNS for lighting up live tiles and raising notifications to users. Developers should become familiar with the WNS documentation on MSDN before attempting to use WNS with a lock screen. For more information, see Push notification overview.

You will need a secret key that has been provisioned through the Windows Store to send push notifications to WNS. For more information about authenticating with WNS and configuring your app, see How to authenticate with the Windows Push Notification Service (WNS).

The following steps show how to send a raw push notification to a lock screen app.

  • Register for a WNS push notification channel and send it to your server.
  • Send a properly formatted raw push notification to WNS using the notification channel.
  • Write a background task that gets activated from a raw push notification.

Raw push notifications are delivered to a client app using a developer’s app server by performing an HTTP PUSH of a well-formed XML payload to a notification channel. A notification channel is generated by the client app, sent to your app server, and used to send the push notification. The notification channel is unique to your app’s instance on the user’s account on Windows 8.1.

JJ679947.wedge(en-us,WIN.10).gifRegister for a push notification channel and send it to your server

  1. Register for a channel by calling one of the CreatePushNotificationChannelForApplicationAsync methods on the PushNotificationChannelManager class in the Windows.Networking.PushNotifications namespace.

    This will generate a push notification channel for your app, which will look something like the following:

    https://db3.notify.windows.com/?token=AQQAAADX3Wr8MA%2fCoZk4n1CmR5ZU7tdic6ksvG4TQq1tiyZtpetjfzuPHSjvliEeqaqJcPuo1jrVnbyCZvnbuU%2byLvZNDONTgUNu6lavpl5EGtWx7iQgpGkyHLbZeosxioQ42Cg%3d
    
  2. Send the channel to your server. Channels expire after 30 days, so there are best practices:

    • Register to get a new push notification channel every time your app starts, and send it to your server to replace the channel previously tied to the user.
    • For a local computer that is always powered, run a background task to renew the channel every once in a while before the channel expires. This is known as a maintenance timer.

JJ679947.wedge(en-us,WIN.10).gifRegister a background task to activate from a raw push notification

  1. To build a background task that runs when a raw push notification is received, you must specify the JavaScript source file that contains code that is to be activated by the background task. To do this, you must ensure your app manifest points to the source file for the background task. The app manifest must contain the name of JavaScript source file for the background task.

    The following sample adds extensions for a PushNotifyTask background task under the <Application> element in an app manifest.

      <Extensions>
        <Extension Category="windows.backgroundTasks" StartPage="js\backgroundTask.js">
          <BackgroundTasks>
            <Task Type="pushNotification" />
          </BackgroundTasks>
        </Extension>
      </Extensions>
    
  2. The app needs to open the channel for raw push notifications.

    The following sample shows how to open a channel for a raw push notification.

    
        // Open the channel. See the "Push and Polling Notifications" sample for more detail
        function openNotificationsChannel() {
            var channelOperation = pushNotifications.PushNotificationChannelManager.createPushNotificationChannelForApplicationAsync();
            WinJS.log && WinJS.log("Opening a channel...", "sample", "status");
            return channelOperation.then(function (newChannel) {
                WinJS.log && WinJS.log("Channel request succeeded!", "sample", "status");
                document.getElementById("scenario1ChannelOutput").value = newChannel.uri;
                SdkSample.channel = newChannel;
            },
                function (error) {
                    WinJS.log && WinJS.log("Could not create a channel (error number: " + error.number + ")", "sample", "error");
                }
            );
        }
    
  3. The app must also register the background task to be activated when a raw push notification is received.

    The following sample shows how to register a background task for a raw push notification.

        // Register the background task for raw notifications
        //
        function registerBackgroundTask() {
            var taskBuilder = new background.BackgroundTaskBuilder();
            var trigger = new background.PushNotificationTrigger();
            taskBuilder.setTrigger(trigger);
            taskBuilder.taskEntryPoint = sampleTaskEntryPoint;
            taskBuilder.name = sampleTaskName;
    
            try {
                var task = taskBuilder.register();
                task.addEventListener("completed", backgroundTaskComplete);
                WinJS.log && WinJS.log("Background task registered", "sample", "status");
            } catch (e) {
                WinJS.log && WinJS.log("Registration error: " + e.message, "sample", "error");
                unregisterBackgroundTask();
            }
        }
    
        function unregisterBackgroundTask() {
            var iter = background.BackgroundTaskRegistration.allTasks.first();
            while (iter.hasCurrent) {
                var task = iter.current.value;
                if (task.name === sampleTaskName) {
                    task.unregister(true);
                    return true;
                }
                iter.moveNext();
            }
            return false;
        }
    
  4. You also need to provide code for the function that runs when the background task is triggered.

    For more information on how to write a background task to receive background network notifications that use raw push notifications, see How to write a background task for raw push notifications.

    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. This means that any callbacks for the network transport must not be affinitized to the UI Single Thread Apartment (STA). Any object that has an affinity to the UI STA (also called the app STA) must not be accessed by background tasks.

    When your code is executing in the background task, you can set up your app for activation, synchronize state between the client and server, and raise a notification to the user.

     

Raw push notifications are similar to badge and tile notifications. The key difference is that the payload of a raw push notification does not contain attributes that update parts of the Windows 8.1 user interface. The payload of the raw push notification is all context data that gets passed directly to your app when the background task is activated. Your app must understand the format of the context data sent by the server.

Before your server can send a raw push notification you must do the following:

JJ679947.wedge(en-us,WIN.10).gifSend a raw push notification to the channel and activate the background task

  1. Ensure that you have registered your app with the Windows Store and have a private key and package SID.

  2. Write code on your app server to authenticate with WNS using the private key and package SID before sending a push notification from the server.

  3. Properly craft a WNS raw push notification and perform an HTTP POST to the notification channel that you have previously received from the Windows Runtime app. The HTTP POST should include several additional HTTP headers:

    • X-WNS-Type=wns/raw
    • Content-Type=application/octet-stream
    • Authorization=The string “Bearer”, a space, and then the authorization token received from the authentication step

    The body of the HTTP POST should include any context that you want to provide to the client app when it runs the background task triggered by receiving the raw push notification. The maximum amount of data that can be included in the raw notification payload is 5KB.

    When the notification is received by the client, the background task is activated and the data payload specified is passed in and accessible through your app’s background task code.

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.

Further steps

For more information on how to write a background task to receive background network notifications that use raw push notifications, see How to write a background task for raw push notifications.

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

Guidelines and checklist for raw notifications

How to authenticate with the Windows Push Notification Service (WNS)

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

How to write a background task for raw push notifications

Lock screen overview

Push notification overview

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

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