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
InitializeComponent();

// Phone-specific initialization
InitializePhoneApplication();

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:
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.AsymmetricDsl:
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Atm:
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.BasicIsdn:
break;
case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
break;
//rest omitted...


Technorati Tags:

No comments:

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