22 November, 2010

WP7: How to detect if I have a valid network connection?

Building a remote logviewer, I was in need of calling out to a webservice to retrieve logging lines for display on the mobile device (Windows Phone 7 application). Now – it turned out that I sometimes lost network connection on the phone which ultimately led to exceptions I had never anticipated in my application logic. Due to this reason – I found the below procedure to work that advices my application logic that there is no network coverage, which allows for taking the proper measures in the code.

First – set up an eventhandler in app.xaml.cs (your main application file) that listens to changes in network connection. A change in network connection will provide you with a new network address, hence this event will be used to provide you with info on “network state”.

// Constructor
public App()
// Global handler for uncaught exceptions.
// Note that exceptions thrown by ApplicationBarItem.Click will not get caught here.
UnhandledException += Application_UnhandledException;

// Standard Silverlight initialization

// Phone-specific initialization

PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;

NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

After this event hooking – you can handle the different networkstates. Here retrieve the currently active network  interface type. In particular – the NetworkInterfaceType.None is important, as this indicates that you have lost network connection completely and it therefore makes no sense attempting to make a call (e.g. http-request) from your application.

        void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)
var type = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;

switch (type)
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.AsymmetricDsl:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Atm:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.BasicIsdn:
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
//rest omitted...

Technorati Tags:



The website is looking bit flashy and it catches the visitors eyes. Design is pretty simple and a good user friendly interface. vShare iOS 11

2009 DREAM said...

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. Jailbreak iOS 11.3

Sample Data said...


iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...