Handling Sometimes-On Connectivity In Windows Phone Apps
There are a lot of conditions that you have to deal with when creating mobile applications that do not present themselves in other types of development. The largest elephant in the room is the unpredictable nature of network connectivity. This doesn’t just affect if you can send a message across the internet but also your location services. And strangely enough there are times where you may have one and not the other because of the type of network you are currently accessing.
The first connection you need to address is to the internet. Unfortunately checking for an internet connection has a significant performance cost so you want to make sure that you aren’t doing this too often. In order to help with this problem you can subscribe to change notifications.
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
This will give you a chance to react when either the type of network changes or you no longer have a network connection. The approach that I have taken up to this point to actually determine if a connection exists directly is to check the NetworkInterfaceType as shown below.
if(Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType != Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None)
As I mentioned earlier the second major source of connectivity issues is determining your location. The usual way of getting the geographic location is to create a GeoCoordinateWatcher and handle the change event. The problem is that if there isn’t a connection to a GPS service then this event is never fired. If you are relying on this event then your app will look like it went to sleep. In order to address this issue use the TryStart method on the GeoCoordinateWatcher object so that you can detect when the device is unable to get a response from the location service within the time limit you set.
!watcher.TryStart(false, new TimeSpan(0, 0, 5))
Not having a network connection means that you need other ways to allow the user to continue working offline if possible. This means local data stores of one type or another tied into the application life cycle. Whether you decide to use isolated storage, a local database or the PhoneApplicationService will depend on your situation, but this is the next consideration that you will have to make. The only way you can get around these issues if your application does not need to maintain state. Hopefully these couple of pointers will make your development a little easier.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)