When we want to send or request data from a remote source, such as the Internet, we need to make sure that we can access the network.
In order to access the state of the network, we make use of the ConnectivityManager
instance:
[assembly: UsesPermission( Manifest.Permission.AccessNetworkState)]
ConnectivityManager
instance through the static FromContext()
method:var manager = ConnectivityManager.FromContext(this);
var networkInfo = manager.ActiveNetworkInfo;
null
, then we have no connection at all, but if there is a connection, we can access various properties:if (networkInfo != null) { var isConnected = networkInfo.IsConnected; var type = networkInfo.Type; var subtype = networkInfo.Subtype; }
var wifiInfo = manager.GetNetworkInfo(ConnectivityType.Wifi);
if (networkInfo != null && networkInfo.IsConnected) { // begin download }
Before we attempt to transfer data across a network, we should verify that the network is indeed available. This is especially so for mobile devices, as the user can disable the network at any time as well as go out of range of network points.
On Android, we use the ConnectivityManager
instance to obtain network information such as the type of network and whether it is connected. Once we have the manager, we can obtain information about the current connection, if there is one, using the ActiveNetworkInfo
property. This information allows us to make decisions on whether to actually try and communicate, or maybe wait until a more opportune time.
Obviously, we can only send data when the connection is available, trying to do so otherwise will result in an exception. If there is no connectivity, the client will attempt to send the data, but as it cannot locate the remote host, it will probably throw a WebException
exception with a Status
instance of NameResolutionFailure
.
If we verify that the connection is available first, we can reduce the number of errors that the app has to deal with. If we do not first check for an available connection, we do need to be able to handle the exceptions that will be thrown when the connection fails.
Even if there is a connection available, we need to first check to see whether this request will cause problems for the user in other areas. For example, if the user is using mobile data, we should not download large files, and if we need to do so, it should be confirmed with the user.
We can control when requests are made, and we should ensure that our app can adjust according to the network type, speed, or limits. Data could be requested at a lower resolution, or less frequently, when there is a slower connection. When the connection is faster or has more bandwidth, we could prefetch data.
When we start a download, there may be an instance when the network goes down. We can subscribe to various events and then pause the download, instead of the app crashing. To do this, we register a BroadcastReceiver()method
with the ConnectivityAction
instance.