Namespaces
Variants
Actions

Checking the Internet connection type on Windows Phone

Jump to: navigation, search

This article explains how to get the Internet connection type without blocking the UI.

WP Metro Icon Wifi.png
Article Metadata

Code Example
Tested with
SDK: Windows Phone SDK 7.1

Compatibility
Platform(s): Windows Phone
Device(s): All

Platform Security
Capabilities: NetworkServices

Article
Created: ArchieCoder (07 Sep 2012)
Last edited: hamishwillee (30 Nov 2012)

Contents

Introduction

All Windows Phone applications that use Internet data should always check if there is a valid Internet connection; if there is no connection, a proper message should be displayed to the user. The correct way to check if you have an Internet connection (WIFI, Ethernet, or none) is by checking the property:

NetworkInterface.NetworkInterfaceType

Unfortunately checking this property is a synchronous operation, so calling it in the UI thread can block the UI for many seconds.

This code example provides a utility class you can use to check the interface type in another thread, and shows how you can use this class in your UI.

Note.png
Note: If your application relies on a specific server you might be tempted to simply check the Internet connection by calling the server. This could result in an inaccurate error message if your server is down, since the Internet may be available.

Utility class for checking the connection

The utility class below (included in the sample project) checks the network connection in another thread.

using System.Threading;
using Microsoft.Phone.Net.NetworkInformation;
 
namespace DotNetApp.Utilities
{
public class NetworkTypeEventArgs
{
#region Constructor
 
public NetworkTypeEventArgs(NetworkInterfaceType type, bool hasTimeout = false)
{
Type = type;
HasTimeout = hasTimeout;
}
 
#endregion
 
#region Properties
 
public bool HasTimeout { get; private set; }
 
public bool HasInternet
{
get { return Type != NetworkInterfaceType.None; }
}
 
public NetworkInterfaceType Type { get; private set; }
 
#endregion
}
 
/// <summary>
/// Static class to get the NetworkInterfaceType without blocking the UI thread.
/// </summary>
public static class NetworkInformationUtility
{
#region Fields
 
private static bool _isGettingNetworkType;
private static readonly object _synchronizationObject = new object();
private static Timer _timer;
 
#endregion
 
#region Methods
 
/// <summary>
/// Get the NetworkInterfaceType asynchronously.
/// </summary>
/// <param name="timeoutInMs">Specifies the timeout in milliseconds.</param>
public static void GetNetworkTypeAsync(int timeoutInMs)
{
lock (_synchronizationObject)
{
if (!_isGettingNetworkType)
{
_isGettingNetworkType = true;
 
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
Thread thread = new Thread(GetNetworkType) {IsBackground = true};
thread.Start(timeoutInMs);
}
else
{
FireGetNetworkTypeCompleted(NetworkInterfaceType.None);
}
}
}
}
 
#endregion
 
#region Delegates
 
public delegate void NetworkTypeEventHandler(object sender, NetworkTypeEventArgs networkTypeEventArgs);
 
#endregion
 
#region Events
 
public static event NetworkTypeEventHandler GetNetworkTypeCompleted;
 
#endregion
 
#region Event Handlers
 
private static void OnTimerElapsed(object state)
{
FireGetNetworkTypeCompleted(NetworkInterfaceType.None, true);
}
 
#endregion
 
#region Private Methods
 
private static void GetNetworkType(object state)
{
_timer = new Timer(OnTimerElapsed, null, (int)state, 0);
 
// This is a blocking call, this is why a thread is used to let the UI to be fluid
NetworkInterfaceType type = NetworkInterface.NetworkInterfaceType;
 
_timer.Dispose();
_timer = null;
 
FireGetNetworkTypeCompleted(type);
}
 
private static void FireGetNetworkTypeCompleted(NetworkInterfaceType type, bool hasTimeout = false)
{
lock (_synchronizationObject)
{
if (_isGettingNetworkType)
{
_isGettingNetworkType = false;
 
NetworkTypeEventHandler networkTypeEventHandler = GetNetworkTypeCompleted;
 
if (networkTypeEventHandler != null)
{
networkTypeEventHandler(null, new NetworkTypeEventArgs(type, hasTimeout));
}
}
}
}
 
#endregion
}
}

Using the utility class

Here are the steps to use this class in your code:

  1. Add the NetworkInformationUtility.cs to your project.
  2. Attach method to the event NetworkInformationUtility.GetNetworkTypeCompleted.
  3. Call NetworkInformationUtility.GetNetworkTypeAsync(3000 /*timeout in ms*/);
  4. Retrieve the result on the GetNetworkTypeCompleted method that you attached to the event.


Code sample:

using System.Windows;
using DotNetApp.Utilities;
 
namespace NetworkInformationApp
{
public partial class MainPage {
public MainPage()
{
InitializeComponent();
}
 
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
 
NetworkInformationUtility.GetNetworkTypeCompleted += GetNetworkTypeCompleted;
 
NetworkInformationUtility.GetNetworkTypeAsync(3000); // Timeout of 3 seconds }
 
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
 
NetworkInformationUtility.GetNetworkTypeCompleted -= GetNetworkTypeCompleted;
}
 
private void GetNetworkTypeCompleted(object sender, NetworkTypeEventArgs networkTypeEventArgs)
{
string message;
 
if (networkTypeEventArgs.HasTimeout)
{
message = "The timeout occurred";
}
else if (networkTypeEventArgs.HasInternet)
{
message = "The Internet connection type is: " + networkTypeEventArgs.Type.ToString();
}
else {
message = "There is no Internet connection";
}
 
// Always dispatch on the UI thread Dispatcher.BeginInvoke(() => MessageBox.Show(message));
}
}
}

Summary

Thank you for reading my first Wiki page! I hope that if your app uses Internet resources you'll use my class.

Download the sample project: File:NetworkInformationApp.zip

This page was last modified on 30 November 2012, at 08:19.
361 page views in the last 30 days.
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.

京ICP备05048969号  © Copyright Nokia 2013 All rights reserved