Partilhar via


Staying connected in the background (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 maintain network connections when a Windows Store app is in the background.

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

Lifecycle model for Windows Store apps

Windows 8 introduces a new lifecycle model for Windows Store apps that differs from the model used for Windows 8 desktop apps and apps on previous version of Windows. By default, a Windows Runtime app is completely suspended from operation when the app is moved to the background. There are a few exceptions to suspending an app (actively printing, accessing an audio stream, and transferring files in the background using Windows.Networking.BackgroundTransfer, for example). For some of these exceptions (Windows.Networking.BackgroundTransfer, for example), the app may still be suspended but Windows continues the network transfer in a separate process.

This new model for Windows Runtime apps improves responsiveness for the app running in the foreground while reducing overall power used by the system. Lower power use improves the length of time that battery-powered system can operate before being recharged. In addition, this new model provides a mechanism for apps that need to work in the background (such as Voice over Internet Protocol (VoIP), instant messaging (IM), and email) to provide an always-connected experience for the end user. This means that an app that depends on a long-running network connection to a remote server can still work when the app is suspended. These are competing demands between being always connected for a real-time app and also trying to reduce power usage and increase app responsiveness.

In order to enable real-time networking scenarios for a Windows Store app that needs to be always connected, several new features introduced in Windows 8 can be used:

  • Background tasks
  • System trigger for SessionConnected
  • Time triggers
  • Windows Push Notification Services (WNS)
  • Raw push notifications
  • Network triggers (receive incoming network packets and maintain network keep-alives)

These features provide support for always connected apps that need to receive incoming network packets or raw push notifications when a Windows Store app is suspended. These apps are also described as being always reachable. The focus of this topic is on how a developer can use WNS and raw push notifications or use network triggers to build a real-time always connected app. These features require that the app also be a lock screen app.

Other background tasks features can also be used by a network app. Some other triggers available for use by a Windows Store app include the following:

  • Maintenance triggers (periodic time events for maintenance)
  • System triggers for users and sessions (user session connected/disconnected, user present/away, and online ID change)
  • System triggers for networking status (network state change, internet available/not available)
  • System triggers for lock screen (app add/remove)

A time trigger could be used when an app does not require real-time connectivity but needs to run for a brief time at some interval. A system trigger could be used when the app needs to be aware of events (for example, the availability of Internet connectivity or user presence). Various triggers can be combined in an app to enable a variety of scenarios. For more information, see Supporting your app with background tasks.

Most Windows Store apps will not need to use the raw push notifications or network triggers detailed in this topic. An app can give the user the impression that it is always running in the background by using a live tile, or by using a live tile with push notifications (other than raw push notifications) from WNS. Your app does not need to be a lock screen app (described later in this topic) or run in the background in order to use a live tile. However, your app must be on the lock screen to use a live tile with raw push notifications or use network triggers.

Requirements for always connected

Two elements are normally required for an app to be always connected and reachable:

  • A long-running process to ensure that any incoming network packets are received and can be quickly processed by the app.
  • A long-running network connection to a remote endpoint that can receive and send data as needed.

In a typical setup, the client is connected to a remote endpoint through intermediate network devices that may include Network Address Translation (NAT) devices, firewalls, and proxy devices. When there is no traffic on the connection, these devices preserve the state of the connection for a limited time. To ensure that the connection remains open between the client and the remote endpoint, network apps often are configured to send some type of a keep-alive message at periodic intervals. This message refreshes the connection lifetime in the intermediate devices and to the server and maintains the connection.

In previous versions of Windows, apps stay running when they lose focus (in the background). These apps can maintain long-running connections when in the background since they can send and receive data and keep-alive messages. Allowing apps to run in the background consumes resources that can affect the responsiveness of other apps and battery life.

Windows Store apps and the lock screen

Windows 8 introduces a new software model that suspends Windows Store apps when they are moved to the background. Once an app is suspended, any packets received by the system may not be immediately delivered to the app and incoming network packets may be dropped. No new packets are sent when the app is suspended. As a result of these conditions, existing network connections may be closed.

To be always connected, an app needs to be a lock screen app. A lock screen app is a special type of app that can display notifications on the lock screen and run code in the background when the app is not in the foreground. Only apps that use one or more background tasks may be lock screen apps.

Lock screen apps have some special abilities:

  • Able to receive a raw push notification from WNS that can run code when the notification is received.
  • Able to maintain a persistent transport connection in the background to a remote service and run code when data is received or a keepalive packet needs to be sent using the network trigger features.
  • Able to run code when a time trigger occurs.
  • Able to run code when a user session is started.

Apps pinned to the lock screen can present information to the user when in the background by updating and displaying a badge icon on the lock screen when there is new information. These apps can also display an on-screen notification when a message arrives. If the notification is tapped or clicked, the user is asked to unlock the device. When the device is unlocked, the app corresponding to the notification is launched with context information.

There are some significant limitations placed on lock screen apps. A user can have a maximum of seven lock screen apps at any given time. A user can add or remove an app from the lock screen at any time.

Lock screen apps are great at providing information to users for things they may have missed when they were away from their device. It is also great for providing on screen notifications for events that may require immediate user action, such as an incoming phone call, incoming instant message, or urgent email.

Most apps will not need to be lock screen apps. When an app is suspended in the background it can use push notifications (other than raw push notifications) from WNS to update a live tile and give users the impression that the app is running, alive and fresh with content. Apps can also use WNS to raise a toast notification to the user at any time or to update the badge count on the app’s tile.

Because there are a limited number of lock screen app slots, you should plan to build your app in such a way that it works even without lock screen app permissions. The user must explicitly allow an app to be added to the lock screen. Your app should always work when it is visible in the foreground. Being a lock screen app simply allows your app to enable some of the same scenarios while in the background.

There are two primary features that allow an app to receive incoming network packets when the app is in the background

  • Raw push notifications that are received by the system and result in running a background task in the app. Using this feature, the app receives the raw data from Windows Push Notification Service (WNS). The contents of this data must be understood by the app. The app must register with WNS to receive the raw push notification.
  • Network triggers using ControlChannelTrigger that run a background task to receive incoming network data or send network keep-alive packets. Note  ControlChannelTrigger is not supported on Windows Phone.  

Several mechanisms discussed below can be used to enable real-time scenarios for apps that are placed on the lock screen. Each has its benefits and tradeoffs. The mechanisms are not mutually exclusive and can be combined in some apps.

Using WNS in Windows Runtime apps

WNS is a cloud service hosted by Microsoft for Windows 8 that can be used by Windows Store apps to receive notifications that can run code, update a live tile, or raise an on-screen notification. In order to use WNS, the local computer must be connected to the Internet so that the WNS service can communicate with it. For more information, see Push notification overview

A Windows Runtime app in the foreground can use WNS to update live tiles, raise notifications to the user, or update badges. Apps do not need to be on the lock screen to use WNS. You should consider using WNS in your app if it must run code in response to a push notification.

For apps that do not have to be on the lock screen (most apps), WNS can be used to provide a live tile update.

If you pin your Windows Runtime app to the lock screen and use WNS in the background, the app can receive notifications from WNS in real time and show them on the lock screen as either a badge update or a notification. When a raw push notification is delivered to a lock screen app, the app can run code in response to the notification. WNS use can be more power efficient than using network triggers.

WNS offers a number of benefits:

  • WNS offers the most power-efficient mechanism for delivering real-time notifications to lock screen apps.
  • WNS simplifies the developer model for your app. In most scenarios, developers do not have to write any background tasks, because the operating system renders the tiles or toast. In a small subset of scenarios, if your app must run a background task, it need only register for the raw push notification and the background task.
  • No persistent socket connection needs to be maintained between the client app and a remote server because Windows maintains the connection to WNS. As a result, the overhead of sending keep-alive messages is not required.
  • A single WNS connection between the client and the cloud service can support all apps on the local computer, which translates to potential battery life efficiency for the client.
  • The operational cost may be reduced for the service on the server side because there is no need to maintain many parked TCP socket connections between the client and the remote service.
  • Your app does not have to reside in memory at all times, because it can be terminated and still have WNS update the tile, raise a toast, or trigger a background task to run upon receipt of an incoming raw push notification.
  • Background tasks that use raw push notifications can be written in JavaScript, C++, and using the .NET Framework 4.5 in C#, VB.NET, or managed C++ for Windows 8.1, Windows Phone 8.1, and Windows Server 2012 R2. Background tasks that use the network trigger feature are not available in JavaScript.

WNS also has some limitations that may affect some apps. WNS is not available to a local computer that is connected to a private home or work network that blocks public Internet access. WNS can also be blocked by some network firewalls even when Internet access is available. There are some other drawbacks using WNS that may need to be considered. Specifically, notifications are delivered on a best-effort basis and there is no guarantee of delivery. The maximum size of the payload in a raw push notification is 5 kilobytes.

Given the advantages, we recommend that developers who build VoIP, IM, or email apps consider using WNS notifications for lock screen apps, but consider alternatives if they do not meet your requirements.

There is no need to build a lock screen app if you simply want to have a live tile update or raise a toast using WNS. A lock screen app is required while using WNS only when the app requires a raw push notification to trigger a background task to run.

For more detailed information on how to use raw push notifications to trigger background tasks, see the following topics:

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

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

How to write a background task for raw push notifications

Guidelines and checklist for raw notifications.

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

Note  ControlChannelTrigger is not supported on Windows Phone devices.

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. Note  HttpClient using SSL is not currently supported using the network trigger feature and ControlChannelTrigger.  
  • 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.  

As with WNS-based lock screen apps, any app that uses the network trigger feature must first request that the app be placed on the lock screen.

After your app has the ability to request lock screen permission, your app must register for the trigger and associate a background task that should be run when the trigger occurs.

The network trigger feature supports two network trigger types:

  • The push notification network trigger provides the capability for a Windows Store app to process incoming network packets on a connected TCP socket even if the app is suspended. The connected TCP socket is sometimes referred to as the transport object or control channel. For the notification to reach the client app, this control channel must exist between the remote endpoint and the client. This control channel must be created by the client app in order for incoming network packets on this channel to trigger a background task. You can think of a control channel as a persistent TCP transport connection that is maintained by Windows and is maintained even when your application is in the background. The push notification network trigger for a ControlChannelTrigger object is returned by the PushNotificationTrigger property. Note  The push notification trigger type is not related at all to push notifications and WNS.  
  • The keep-alive network trigger provides a capability for the app to be suspended and send a keep-alive packet to the remote endpoint. This is important to help maintain the transport connection so the remote endpoint server does not close the connection. There is also a variant where a server-initiated keep-alive can also keep the control channel alive. The keep-alive network trigger for a ControlChannelTrigger object is returned by the KeepAliveTrigger property.

A lock screen app that uses the network trigger feature must register for the push notification trigger and should register for the keep-alive trigger. Together this ensures connectivity between the client and remote endpoint when the app is suspended.

The network trigger feature supports two possible resource types for a push notification or keep-alive network trigger:

Hardware slot - Allows the app to use background network notifications even in low-power or connected-standby mode.

  • Hardware slot - Allows the app to use background network notifications even in low-power or connected-standby mode.
  • Software slot - Allows the app to use background network notifications but not in low-power or connected-standby mode.

This notion of slot is integral to the network trigger and is not required for WNS.

One of the options to specify while registering for the network trigger feature is the hardware or software slot resource type. This resource type capability provides a way for your app to be triggered by an incoming notification even if the device is in low power mode. By default, a software slot is selected if the developer does not specify an option. A software slot allows your app to be triggered when the system is not in connected standby. This is the default on most computers.

On the other hand, a hardware slot allows your app to be triggered at all times including when the system is in connected standby. Only systems with network devices that support connected standby will have a hardware slot. Note that the app cannot be triggered through a software or hardware slot when the system is in Sleep or Hibernate mode, or is shut down.

An app can create and use a maximum of 5 network triggers. There is also an additional system limitation on number of network triggers that specify hardware slots. The first 3 lock screen apps that register for a hardware slot for a network trigger can use a maximum of 3 hardware slots per app. Any other lock screen apps beyond the first three apps registered for hardware slots are limited to only software slots for their network triggers.

For more detailed information on how to use network triggers, see the following topics:

How to create a lock screen app that uses background network triggers

How to use network triggers to deliver notifications to a lock screen app

How to write a background task for a network trigger

How to re-establish a network trigger and transport connection

How to use a stream socket with a network trigger

How to use a WebSocket with a network trigger

How to use HttpClient with a network trigger

How to use IXMLHttpRequest2 with a network trigger

Guidelines and checklist for using network triggers

Using time triggers or system event triggers in Windows Store apps

Lock screen apps can be configured to run code periodically using a time trigger with a minimum interval of 15 minutes. One example is the need to poll for new e-mail messages, possibly when an app is connected to a POP3 or IMAP email server.

Lock screen apps can also use a system event trigger to run code when the user logs on to the local computer (system trigger for session start). One example is signing in the user in to an instant message service when they start a user session, so instant messages can be received.

In this topic, we focus on building lock screen apps using raw push notifications with WNS or the network trigger feature. For more information on using a timer, see How to run a background task on a timer. For more information on background tasks, see Supporting your app with background tasks.

Limit on the number of control channels

When your app is placed on the lock screen, your app can create and configure ControlChannelTrigger objects and use network triggers. However, the number of such ControlChannelTrigger objects that can be used by an app are limited. An app can register a maximum of five ControlChannelTrigger objects.

The table below lists the number of ControlChannelTrigger objects that can be created with resource type of hardware and software for apps that include in their app manifest a background task type of controlChannel.

A hardware slot would be used for a ControlChannelTrigger object used to receive network packets when in connected standby.

Lock screen app Number of hardware slots Number of software slots
First 3 lock screen apps 3 2
Apps 4 to 7 0 5

 

An app on the lockscreen can create and register up to five ControlChannelTrigger objects. The first 3 lock screen apps are special and can create and register ControlChannelTrigger objects for up to three hardware slots of the possible 5 ControlChannelTrigger objects (up to 3 hardware slots and 2 software slots). Any of these first 3 lockscreen apps could also choose to create all five ControlChannelTrigger objects as software slots. Apps number 4 through 7 on the lockscreen can only create and register ControlChannelTrigger objects for software slots.

If an app concurrently requests more than the permitted number of ControlChannelTrigger objects, it will get a policy error when the WaitForPushEnabled method returns.

When an app requests to be added to the lockscreen, a status value (BackgroundAccessStatus) is returned. If a status value of AllowedWithAlwaysOnRealTimeConnectivity is returned, the app has the ability to request either hardware or a software slot. If a status value of AllowedMayUseActiveRealTimeConnectivity is returned, the app only has the ability to request a software slot. If a status value of Denied is returned, the app cannot request either a hardware slot or a software slot and calls to register a ControlChannelTrigger object will fail. If the app marked only controlChannel for all background tasks in the app manifest, then the status value returned can only be AllowedWithAlwaysOnRealTimeConnectivity or Denied. If the app had marked controlChannel for a background task and had marked a different value for some other background task (timer for example) in the app manifest, then any of the 3 possible status values can be returned.

The table above is true for devices that support connected standby. In order to support connected standby, both the device chipset and the network hardware must support the ability to receive packets even when the device goes into sleep or standby mode. For devices with chipsets which do not support connected standby, the notion of hardware slots and wake from sleep/hibernate are not supported. Hence, registering ControlChannelTrigger objects will fall back to software slots even if requested for hardware slots. On some computers where the device chipset supports connected standby but the network hardware does not support connected standby, the ControlChannelTrigger registration will return an error (WaitForPushEnabled returns a ControlChannelTriggerStatus value of SystemError). This indicates that the app tried to register for the hardware slot, but failed because the network hardware is not capable of supporting connected standby (a hardware slot). In this scenario, the app will be unable to support network triggers when the device enters connected standby.

If your app is lock screen app number 4 through 7, it will only get access to software slots. Incoming notifications will be delivered only when the machine is not in connected standby. So the app cannot deliver reliable real-time connectivity to the end user.

If an app is placed on the lock screen position as app number 4 through 7 which allow only software slots, only the user can fix this problem. The user can change the order of the apps on lock screen by removing and re-adding applications on lock screen so that the app can receive a hardware slot.

Background task and sandboxing

The lifetime of a background task is determined by the IBackgroundTask.Run method on the background task. To ensure that background tasks do not adversely affect battery life, Windows enforces a limit in terms of CPU and network I/O resources an app can use during background tasks. Each app gets a quota of these resources on a periodic basis, and exhausting this quota suspends your app's background task. An app must be resilient to being suspended due to sandboxing.

For more information, see Supporting your app with background tasks.

Further steps using raw push notifications

For more information on how to create a lock screen app to receive background network notifications that use raw push notifications, see How to 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.

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.

Further steps using network triggers

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

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.

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

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

Badge overview

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

Lock screen overview

Push notification overview

Supporting your app with background tasks

Tile and tile notification overview

Toast notification overview

Transferring data in the background

Troubleshooting and debugging network connections

Reference

ControlChannelTrigger

HttpClient

HttpClientHandler

IXMLHTTPRequest2

MessageWebSocket

StreamSocket

StreamWebSocket

System.Net.Http

Windows.ApplicationModel.Background

Windows.Networking.BackgroundTransfer

Windows.Networking.PushNotifications

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

Push and periodic notifications client-side sample

Raw notifications sample