WP7 Development Tip of the Day: Detecting changes to the internet connection

by brad 18. November 2010 15:42

Like the previous tip on detecting if a phone’s internet connection is available, today’s tip comes from the System.Net.NetworkInformation namespace.  The NetworkChange class has a handy event called the NetworkAddressChanged event.  This event is called when the phone gets a new IP address.

   1: public MainPage()
   2: {
   3:     InitializeComponent();
   4:     NetworkChange.NetworkAddressChanged += NetworkAddressChanged;
   5: }
   6:  
   7: static void NetworkAddressChanged(object sender, EventArgs e)
   8: {
   9:     throw new NotImplementedException();
  10: }

Since getting a new IP address is not quite the same as going online or offline, it takes a little more doing to find out if the phone’s connection status has really changed.  This is where our previous tip comes in handy.  You can use the NetworkInterface class to check if the phone has a connection.

   1: public MainPage()
   2: {
   3:     InitializeComponent();
   4:     NetworkChange.NetworkAddressChanged += NetworkAddressChanged;
   5: }
   6:  
   7: private static void NetworkAddressChanged(object sender, EventArgs e)
   8: {
   9:     if (!InternetIsAvailable())
  10:         MessageBox.Show("You just lost your internet connection.");
  11: }
  12:  
  13: private static bool InternetIsAvailable()
  14: {
  15:     return !NetworkInterface.GetIsNetworkAvailable();
  16: }

Of course, an app that pops up a message box every time the phone loses its internet connection would be madness.  But it shows the general concept

Other Resources

More Tips

Tags:

Comments

11/22/2010 1:54:42 PM #

trackback

Archived Tip of the Day by Category

Archived Tip of the Day by Category

code badger

Comments are closed

About Brad

Brad Tutterow lives in Illinois and works in Missouri. He has 12 years of experience developing web sites and Windows applications using a variety of technologies and is most excited currently about Silverlight, Windows Phone 7, Halo Reach, and Visual Studio 2010.