次の方法で共有


How to manage network connection events and changes in availability (XAML)

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 C# or C++ and are based on the Network information sample. For general help creating a Windows Runtime app using C# or Visual Basic, see Create your first Windows Runtime app using C# or Visual Basic. For general help creating a Windows Runtime app using C++, see Create your first Windows Runtime app using C++.

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 and when Windows 8 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 into 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 in use.

Taking all of these possibilities into consideration, there is more than enough reason to equip your app with the logic that allows for smart choices when encountering changes to with network availability. Still, 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

Your app can only adapt to changing network states if it knows when they have occurred. The following example registers for notification of NetworkStatusChanged events for a specific connection.

void NetworkStatusChange()
{
    // register for network status change notifications
    try
    {
        networkStatusCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);
        if (!registeredNetworkStatusNotif)
        {
            NetworkInformation.NetworkStatusChanged += networkStatusCallback;
            registeredNetworkStatusNotif = true;
        }
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Unexpected exception occured: " + ex.ToString(), NotifyType.ErrorMessage);
    }
}

Retrieving the connection state change information

When a status change occurs for the Internet connection profile, the following event handler example retrieves the ConnectionProfile associated with the event and displays the connection status information, which includes the current scope, type, and cost of connectivity as defined by NetworkConnectivityLevel, NetworkTypes, and NetworkCostType.

async void OnNetworkStatusChange(object sender)
{
    try
    {
        // get the ConnectionProfile that is currently used to connect to the Internet                
        ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

        if (InternetConnectionProfile == null)
        {
            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                rootPage.NotifyUser("Not connected to Internet\n", NotifyType.StatusMessage);
            });
        }
        else
        {
            connectionProfileInfo = GetConnectionProfile(InternetConnectionProfile);
            await _cd.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                rootPage.NotifyUser(connectionProfileInfo, NotifyType.StatusMessage);
            });
        }
        internetProfileInfo = "";
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Unexpected exception occured: " + ex.ToString(), NotifyType.ErrorMessage);
    }
}

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 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 whether or not to switch to the new network.

For example, 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:

1. Check network cost and retry the network operation if a better connection is available. Windows automatically selects the unrestricted over the metered network and the faster network over the slower one if available.

2. On retrying, if the network operation succeeds, cancel the original network operation on the previous network if it exists.

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.

 

Note  Advanced developers may also choose to optimize app behavior when retrying network operations. For example, you may want to replace an existing connection with a new connection over a higher speed network. In this scenario, a developer can use the Sockets APIs, like StreamSocketInformation.BandwidthStatistics, to determine if switching to another connection is appropriate.

 

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.

Other

Create your first Windows Runtime app using C# or Visual Basic

Create your first Windows Runtime app using C++

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 usage data

Reference

ConnectionProfile

NetworkStatusChanged

Windows.Networking.Connectivity

Samples

Network information sample

Network status background sample