Obtaining a network state
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.
How to do it...
In order to access the state of the network, we make use of the ConnectivityManager
instance:
When we want to access the state of the network, we have to request permission from Android first:
[assembly: UsesPermission( Manifest.Permission.AccessNetworkState)]
Now that we have permission, if we want the network state, we need to get hold of the
ConnectivityManager
instance through the staticFromContext()
method:var manager = ConnectivityManager.FromContext(this);
Once we have the manager, we can get hold of the current state:
var networkInfo = manager.ActiveNetworkInfo;
If the info is
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...