I've been working on a project where there was little point in synchronising data if the Mobile device was out of network range (for obvious reasons)
So rather than wait for an HTTP timeout type error thrown by the SQL Compact Merge replication, I needed a quick way to determine if the mobile device is connected to any sort of network.
This bit of code has been kicking about for a while and it simply returns if the mobile device has any IP address other than that of localhost -
public static bool OnNetwork() { IPHostEntry mydev = Dns.GetHostEntry(Dns.GetHostName()); for (int nindex = 0; nindex < mydev.AddressList.Length; nindex++) { string aux = mydev.AddressList[nindex].ToString(); if (aux != "127.0.0.1") return true; } return false; }
So putting the above bit of code in a background thread and calling it periodically is a nice simple way to detect if a device is in network range. I then raise an event if the state changes.
Now I know what your thinking? Windows Mobile 5/6 ships with the 'State and Notification Broker API'. Given this I thought I ought to update my approach for newer devices. Reading -
http://www.developer.com/ws/pc/article.php/3547381
I thought it would make sense to implement it this way as it is much less hassle than a background thread. So the code behind a simple form to achieve this, looks like this.
namespace DeviceApplication10 { public partial class Form1 : Form { SystemState foundnet = new SystemState( SystemProperty.ConnectionsNetworkCount); private bool onnetwork() { IPHostEntry mydev = Dns.GetHostEntry(Dns.GetHostName()); for (int nindex = 0; nindex < mydev.AddressList.Length; nindex++) { string aux = mydev.AddressList[nindex].ToString(); if (aux != "127.0.0.1") return true; } return false; } public Form1() { InitializeComponent(); foundnet.Changed += new ChangeEventHandler(foundnet_Changed); } void foundnet_Changed(object sender, ChangeEventArgs args) { if (onnetwork()) { // do some stuff as we are now on the network, like work out SSID of current wireless network etc. } } } }
The above event fires when the number of network connections change. I then do a quick call to my onnetwork() method when the event fires, just to be certain than we can talk to the outside world.
So, why is this post called Drive By? Well the above allows my Windows Mobile device to automatically detect when I park my car at home as it knows when I'm on my home wireless network. Geeky but cool...
Theme design by Jelle Druyts
Pick a theme: BlogXP calmBlue
My Virtual Earth Balloon Races www.racingballoon.com Richard JonesPowered By The Fridge Server