How to manage network connection events and changes in availability (HTML)
This topic shows how to register to receive notifications for network connection state changes and retrieve the current state information using classes in the Windows.Networking.Connectivity namespace.
We also provide recommendations for app behavior that will support a consistent user experience in network scenarios.
Prerequisites
The following examples use JavaScript and are based on the Network information sample. For general help creating a Windows Runtime app using JavaScript, see Create your first Windows Runtime app using JavaScript.
Knowing what a ConnectionProfile is and how to access the information that it represents is important; for more information see How to retrieve network connection information. For additional code examples, download the Network Information sample.
What qualifies as a connection state change event?
State change events indicate changes in the availability, type, or cost of connectivity offered by an individual connection. The latest connected apps frequently encounter network traversal scenarios typical of mobile device usage. When the Windows Runtime detects a new network, it will automatically provide it as a new connectivity option. For instance, if a user is using a device on a 3G/4G network to stream data, and later comes in range of a Wi-Fi network, the new connectivity option will be available for the application to leverage. Of course, this also means that a user can move out the range of a network, one that may even be currently in use.
Taking all of these possibilities into consideration, it is important to equip your app with logic that allows for smart choices when encountering changes in network availability. Existing network connections will not automatically switch over to other connections seamlessly. Your app needs to register for networkstatuschanged events and adapt accordingly.
Registering for notifications of connection state change events
Before your app can adapt to changing network states it needs to know when they occur. The following example code shows how to register for event notifications for networkstatuschanged for a specific connection profile.
You must write code to handle exceptions when you call most asynchronous network methods. Also the methods in the Windows.Networking.Connectivity namespace that register for event notifications or tries to retrieve a ConnectionProfile can throw exceptions. Your exception handler can retrieve more detailed information on the cause of the exception to better understand the failure and make appropriate decisions. For more information, see How to handle exceptions in network apps.
// Define some variables used // A variable to store network status change information var internetProfileInfo = ""; // A boolean to keep track of registration for network status change notifications var registeredNetworkStatusNotif = false; var networkInfo = Windows.Networking.Connectivity.NetworkInformation; //Register for Network Status Change notifications, and display new Internet Connection Profile information on network status change function registerForNetworkStatusChangeNotif() { // register for network status change notifications if (!registeredNetworkStatusNotif) { try { networkInfo.addEventListener("networkstatuschanged", onNetworkStatusChange); registeredNetworkStatusNotif = true; if (internetProfileInfo === "") { mySample.displayStatus("No network status change. ", "sample", "status"); } catch (e) { mySample.displayError("An unexpected exception occured: " + e.name + ": " + e.message); } } }
When a network scenario changes, your app may need to unregister from network status change notifications if already registered and then re-register for notifications for the new network scenario.
//Unregister for Network Status Change notifications function unRegisterForNetworkStatusChangeNotif() { try { networkInfo.removeEventListener("networkstatuschanged", onNetworkStatusChange); internetProfileInfo = ""; } catch (e) { mySample.displayError("An unexpected exception occured: " + e.name + ": " + e.message, "sample", "error"); } }
Retrieving the connection state change information
When a status change occurs, the following example of an event handler retrieves the associated ConnectionProfile for the current Internet connection profile. This ConnectionProfile can be used to retrieve and display connection status information, which includes the current scope, type, and cost of connectivity as defined by NetworkConnectivityLevel, NetworkTypes, and NetworkCostType.
// Event handler for Network Status Change event function onNetworkStatusChange(sender) { //network status changed internetProfileInfo = "Network Status Changed: \n\r"; try { // get the ConnectionProfile that is currently used to connect to the Internet var internetProfile = networkInfo.getInternetConnectionProfile(); if (internetProfile === null) { mySample.displayStatus("Not connected to Internet\n\r"); } else { internetProfileInfo += getConnectionProfileInfo(internetProfile) + "\n\r"; mySample.displayStatus(internetProfileInfo); } internetProfileInfo = ""; } catch (e) { mySample.displayError("An unexpected exception occured: " + e.name + ": " + e.message, "sample", "error"); } }
There are a variety of network states that can change which result in a network state change event. These include whether the device has a new ConnectionProfile, a new connection cost, connectivity level, and other changes. The above event handler can use the NetworkStateChangeEventDetails class to determine what has changed.
Recommended app behavior when handling connection state changes
The following table outlines the primary connection state change scenarios and provides app behavior recommendations:
| Scenario | Recommended Behavior |
|---|---|
| Connection loss due to error |
Connections can be re-established by simply retrying the network operation. If this fails, then wait for a networkstatuschanged event to retrieve current connection state information. We recommend that apps use an exponentially increasing backoff interval between retries, starting with a value of 50 milliseconds. |
| Loss of network |
Inform the user that the connection has been lost, then register and wait for a networkstatuschanged event. |
| New network availability |
With mobile devices, scenarios involving a single device traversing multiple public and private networks are common. For example, a user may be connected to mobile broadband and chatting with friends using the Messaging app before going home and connecting to an unrestricted home network. The default policy in Windows 8, Windows Server 2012, and Windows Phone 8.1 and later is to prefer an unrestricted network over the metered network, and a faster network over the slower network. However, existing connections established by an app do not automatically switch over to a new network. The app must get involved because only the app can make the best decision on whether or not to switch to the new network. If a video stream download is close to completion, it may not make sense to switch to a new network and restart the download. However if the current network is dropping packets, is too slow, or the stream will take additional time to complete, switching to the new network may be best. If you determine that switching networks is plausible for your app scenario, follow these guidelines when you detect a new network:
|
| Network cost change |
Mobile networks, in particular, often have very specific restrictions placed on usage. If your app encounters a change in network cost due to more than 80% of the mobile broadband data cap consumed, variable cost or roaming, then adapt app behavior as detailed in How to manage metered network cost constraints. |
Summary
In this topic, we reviewed how to register for connection state change notifications and use these notifications to retrieve the current state information from the ConnectionProfile for which the event occurred. We also reviewed recommended app behavior when dealing with the most common state change scenarios.
While this topic covers network availability, in scenarios involving connections to metered networks, a networkstatuschanged event can also represent a change to the cost and data plan properties. For more information and guidance on how best to change app behavior in these scenarios, see How to manage metered network cost constraints.
Related topics
- Other
- Create your first Windows Runtime app using JavaScript
- How to handle exceptions in network apps
- How to manage metered network cost constraints
- How to retrieve network adapter and locality information
- How to retrieve network connection information
- How to retrieve network connection usage data
- Reference
- ConnectionProfile
- NetworkInformation
- networkstatuschanged
- networkStatusChangedEventHandler
- Windows.Networking.Connectivity
- Samples
- Network information sample
- Network status background sample