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:

No comments: