次の方法で共有


Win8 Apps: Check for Network Connectivity

A lot of apps require internet connectivity to function – like my app, Dark Skies.   One thing I overlooked when first releasing Dark Skies was a graceful check for network connectivity.  If the app launches and there is no connectivity, it should fail gracefully and notify the user.  Ideally, we should also plug into the Network Status Changed event handler, so our app is notified when the internet goes up or down during the app’s session.

There are a couple of ways to accomplish this.  If you’re checking for internet connectivity occasionally, you can do something like this:

 public static bool IsNetworkAvailable()
{
    try
    {
        ConnectionProfile profile = NetworkInformation.GetInternetConnectionProfile();
                
        if (profile == null)
        {
            return false;                 
        }
        else
        {                                     
            var networkAdapterInfo = profile.NetworkAdapter;
            if (networkAdapterInfo == null)
            {
                return false;
            }
            else
            {
                return true;                       
            }
        }
    }
    catch (Exception e)
    {
#if DEBUG
        throw;
#endif
        return false;
    }
}

If you’re checking for connectivity frequently, you’ll likely want to cache that result in a variable, and simply change the cached status when the network status changes.  Wiring up the event is pretty simple:

 NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

And then the event handler can do whatever you’d like:

 private async void NetworkInformation_NetworkStatusChanged(object sender)
{
   // ...
}

When the app loads, we’ll display a notification of some kind that internet connectivity is required: 

image

Because the nature of tablets and internet connectivity, the state of the connection may change frequently.  Having a simple way to check for network connectivity and handling changes to the network status is a great way to ensure a smooth user experience!

Oh – it’s also a good idea to check before doing anything that might throw a network-based exception.  For example, on app load, I made the mistake of always acquiring a push notification channel:

 await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

If the network is unavailable, this will throw an exception.  So, be sure to check for network connectivity and/or handle exceptions when setting up push notifications:

 private async void AcquirePushChannel()
{          
    try
    {
        if (IsNetworkAvailable())
        {
            CurrentChannel =
                await PushNotificationChannelManager.
                          CreatePushNotificationChannelForApplicationAsync();
        }
    }
    catch (Exception ex)
    {
#if DEBUG
        throw;
#endif
    }
}