To find out what the state of a network connection is, you need to get an object of type NetworkInfo .
The way to do this is by calling the ConnectivityManager class obtained as follows:
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
An Android device has several types of network connectivity available, including 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 if you have 3G / 4G connection:
ConnectivityManager manager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isConnected = isNetworkConnected(manager, ConnectivityManager.TYPE_MOBILE);
Normally, the active connection is made through:
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = manager.getActiveNetworkInfo();
boolean isConnected = network != null && network.isConnected() && network.isAvailable();
To find out the name of the active connection use:
String connectionName = network.getTypeName();
Do not forget the permission required:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
There is no such thing as "enable the connection to mobile data" , what is activated is the connection to the network / internet .
The active connection type, the one that is returned by manager.getActiveNetworkInfo();
is, within available ones, the lowest cost for the user. If TYPE_MOBILE is available, TYPE_WIFI is active TYPE_WIFI .