Reputation: 28818
I have successfully used the answer to this question to perform a one off check if mobile data is enabled, but I would like to receive a notification of such change, for example when a user goes to this screen:
Is this possible?
Upvotes: 0
Views: 677
Reputation: 1364
public static boolean isNetworkOn(Context context, int networkType) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= 21) {
final Network[] networks = connectivityManager.getAllNetworks();
for (Network network : networks) {
final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == networkType && networkInfo.isConnectedOrConnecting()) {
return true;
}
}
}
else {
@SuppressWarnings("deprecation") final NetworkInfo networkInfo = connectivityManager.getNetworkInfo(networkType);
if (networkInfo.isConnectedOrConnecting()) {
return true;
}
}
return false;
}
Upvotes: 0
Reputation: 634
You can use OnNetworkActiveListener to monitor activation of network data. The ConnectivityManager class can give you infos on the currently active network connection. It would go like this :
ConnectivityManager cm = getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfos networkInfos = cm.getActiveNetworkInfo();
if(networkInfos.isConnected()){
//Do something
} else {
//Do something else
}
Hope it helps.
Upvotes: 1