Partilhar via


How to write a background task for a network trigger (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 in a Windows Store app that uses a network trigger. This topic walks you through writing a background task for the network trigger feature using ControlChannelTrigger.

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 TCP 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.

    This topic does not apply to apps written in JavaScript or a foreground app in JavaScript with an in-process C# or C++ binary. Background network connectivity using a network trigger with ControlChannelTrigger is not supported by a JavaScript app. For 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 that uses incoming raw push notifications to signal that new mail has arrived on the server, the app needs to run code to connect to the email server and get the new email and potentially raise a notification to the user. 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 a network trigger implemented in the ControlChannelTrigger object.

public sealed class controlChannelBuilderActivationClassName : Windows.AppModel.Background.IBackgroundTask
{
    public void Run(Windows.AppModel.Background.IBackgroundTaskInstance taskInstance)
    {
        IControlChannelTriggerEventDetails channelEventArgs = (IControlChannelTriggerEventDetails)taskInstance.TriggerDetails;
        ControlChannelTrigger channel = channelEventArgs.ControlChannelTrigger;
        string channelId = channel.ControlChannelTriggerId;

        string messageReceived = "Network packet received";
          
        //InvokeSimpleToast(messageReceived);
        InvokeRingingToast(messageReceived);
        
        //FlushTransport is required if apps sends data. 
        Channel.FlushTransport();
    }
}

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 network packet, process the packet, 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. This is derived from the IControlChannelTriggerEventDetails object. The context is the channel ID string that apps can use to differentiate between various instances of the channel. This is illustrated in the Run method shown above, where the channelEventArgs variable is used to retrieve the control channel ID.

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: Using network triggers in Windows Store apps

The System.Net.Sockets.ControlChannelTrigger class implements the network trigger feature available for apps that must maintain a persistent transport connection in the background. This is typically needed for connectivity to servers running an older protocol that cannot be modified to use WNS, or when there are concerns about privacy or message service-level agreements (SLAs).

Consider using the network trigger feature if your app server cannot use WNS. For example, an email client that uses a Microsoft Exchange server and is deployed widely within an enterprise cannot be modified to use WNS to send notifications when an email message arrives. The client must maintain a direct network connection to the Microsoft Exchange server.

The ControlChannelTrigger class can be used by instances of the following classes in the Windows.Networking.Sockets that establish a TCP connection:

The ControlChannelTrigger class can also be used by instances of the following that establish a TCP connection:

  • The HttpClient, HttpClientHandler, and related classes in the System.Net.Http namespace in the .NET Framework 4.5. Custom classes that derive from these classes are also supported.
  • The IXMLHTTPRequest2 interface. The IXMLHTTPRequest2 interface is an extension to XMLHttpRequest object defined in several working drafts published by the World Wide Web Consortium (W3C).

The network trigger feature offers a number of benefits:

  • Compatibility with existing client/server protocols that require persistent transport connections.
  • Message delivery guarantees, because the app maintains connection state between the client and the server.

There are also some drawbacks with using the network trigger feature:

  • The network trigger feature is more complex than using WNS because it requires additional components to maintain the transport connection.
  • An app is limited to a maximum of five network triggers.
  • An app using the network trigger feature with other background tasks need to be written in C#, VB.NET, or C++. Note  The ControlChannelTrigger class and related classes are not supported in a Windows Store app using JavaScript. A foreground app using JavaScript with an in-process C# or C++ binary is also not supported.  

Step 3: Previous steps

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

For more information on how to use network triggers to deliver notifications to a lock screen app, see How to use network triggers to deliver notifications to a lock screen app.

Step 4: Further steps

For more information on how to re-establish a network trigger and a transport connection, see How to re-establish a network trigger and transport connection.

For more information on using a StreamSocket with a network trigger, see How to use a stream socket with a network trigger.

For more information on using a MessageWebSocket or StreamWebSocket with a network trigger, see How to use a WebSocket with a network trigger

For more information on how to use HttpClient with a network trigger, see How to use HttpClient with a network trigger.

For more information on how to use with a network trigger, see How to use IXMLHttpRequest2 with a network trigger

For more information on guidelines and checklists for using network triggers, see Guidelines and checklist for using network triggers.

Other resources

Adding support for networking

Background Networking

Lock screen overview

Staying connected in the background

Supporting your app with background tasks

Troubleshooting and debugging network connections

Reference

ControlChannelTrigger

HttpClient

HttpClientHandler

IXMLHTTPRequest2

MessageWebSocket

StreamSocket

StreamWebSocket

System.Net.Http

Windows.ApplicationModel.Background

Windows.Networking.Sockets

Samples

Background task sample

ControlChannelTrigger HttpClient sample

ControlChannelTrigger with IXMLHTTPRequest2 sample

ControlChannelTrigger TCP socket sample

ControlChannelTrigger StreamWebSocket sample

Lock screen apps sample