×
Namespaces

Variants
Actions
Revision as of 03:50, 20 November 2013 by hamishwillee (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Checking the Internet connection type on Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

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

WP Metro Icon Wifi.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone SDK 8/7.0
Devices(s): Nokia Lumia 920, Nokia Lumia 800
CompatibilityPlatform Security
Capabilities: NetworkServices
Article
Created: ArchieCoder (07 Sep 2012)
Last edited: hamishwillee (20 Nov 2013)

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.pngNote: 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

Version Hint

Windows Phone: [[Category:Windows Phone]]
[[Category:Windows Phone 7.5]]
[[Category:Windows Phone 8]]

Nokia Asha: [[Category:Nokia Asha]]
[[Category:Nokia Asha Platform 1.0]]

Series 40: [[Category:Series 40]]
[[Category:Series 40 1st Edition]] [[Category:Series 40 2nd Edition]]
[[Category:Series 40 3rd Edition (initial release)]] [[Category:Series 40 3rd Edition FP1]] [[Category:Series 40 3rd Edition FP2]]
[[Category:Series 40 5th Edition (initial release)]] [[Category:Series 40 5th Edition FP1]]
[[Category:Series 40 6th Edition (initial release)]] [[Category:Series 40 6th Edition FP1]] [[Category:Series 40 Developer Platform 1.0]] [[Category:Series 40 Developer Platform 1.1]] [[Category:Series 40 Developer Platform 2.0]]

Symbian: [[Category:Symbian]]
[[Category:S60 1st Edition]] [[Category:S60 2nd Edition (initial release)]] [[Category:S60 2nd Edition FP1]] [[Category:S60 2nd Edition FP2]] [[Category:S60 2nd Edition FP3]]
[[Category:S60 3rd Edition (initial release)]] [[Category:S60 3rd Edition FP1]] [[Category:S60 3rd Edition FP2]]
[[Category:S60 5th Edition]]
[[Category:Symbian^3]] [[Category:Symbian Anna]] [[Category:Nokia Belle]]

This page was last modified on 20 November 2013, at 03:50.
464 page views in the last 30 days.