To know the status of a network connection it is necessary to obtain an object of type Networkinfo.
The way to achieve this is by resorting to the class Connectivitymanager obtained as follows:
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
A device Android has several types of network connection available, among them TYPE_MOBILE and TYPE_WIFI.
To test whether a particular type is available you can use the following method:
public static boolean isNetworkConnected(ConnectivityManager connectivityManager, int type){
final NetworkInfo network = connectivityManager.getNetworkInfo(type);
if (network != null && network.isAvailable() && network.isConnected()){
return = true;
} else {
return false;
}
}
For example to know if you have 3G/4G connection:
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isConnected = isNetworkConnected(manager, ConnectivityManager.TYPE_MOBILE);
Usually what is used is to get the active connection through:
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = manager.getActiveNetworkInfo();
boolean isConnected = network != null && network.isConnected() && network.isAvailable();
To know the name of the active link use:
String connectionName = network.getTypeName();
Don’t forget the necessary permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
There’s no such thing as "enable mobile data connection", what is active is the link to network/internet.
The type of active link, the one that is returned by manager.getActiveNetworkInfo();
is, within the available, the lowest cost to the user. If available TYPE_MOBILE and the TYPE_WIFI the active is TYPE_WIFI.