WP7dev

Windows Phone 7 development tips

Tag Archives: NetworkInterface

Detecting connection loss / status on Windows phone 7

Knowing the status of the device connection can be very useful, displaying an error when trying to access something on the internet when the device has no connection is good practice. This is one of the points Microsoft loves to look at, especially when selecting featured applications.

There are two ways to handle this :

First is to use NetworkChange class, for example, in your App.xaml.cs constructor :

App.xaml.cs :


public App()

{

    // Standard App() content

    NetworkChange.NetworkAddressChanged += new  

        NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);

}

void NetworkChange_NetworkAddressChanged(object sender, EventArgs e)

{

    if (Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType ==

    NetworkInterfaceType.None)

        Deployment.Current.Dispatcher.BeginInvoke(

            () =>

            {

                MessageBox.Show(StringLibrary.General_NetworkError);

            });

}


Or, check directly where you need to use the connection :


NetworkInterfaceType type = NetworkInterface.NetworkInterfaceType;

if (type == NetworkInterfaceType.None)

{

    // Handle error

}


This can also be used to determine what connection type is being used, simply compare NetworkInterface.NetworkInterfaceType to the possible values of NetworkInterfaceType enum.

Be very careful when using this, as when in bad cellular cover, this call can take up to 20s.


Advertisements