I want my app to check whether "Data network mode" or "Mobile data" is enabled, even if it is not currently active. In other words I need to check whether the app will potentially incur mobile data charges, even if it the phone is currently connected through WiFi.
By googling I have found the following code which checks whether "Mobile data" is "active".
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE;
The problem with this code is that if WiFi is active the Mobile data is not reported as active even if it is switched to on.
Can the code be modified to determine whether mobile data is "enabled" and therefore potentially active, rather than as with this code whether it is the currently active connection mode?
Try this, it works in most cases.
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
if (!isConnected)
{
return false;
}
Try this
ConnectivityManager cm = (ConnectivityManager)
activity.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
I'm not sure this is will work on all devices, but it does work on some I tried:
private boolean isMobileDataEnabled(Context ctx) {
int mobileData = Settings.Secure.getInt(ctx.getContentResolver(), "mobile_data", 0);
return mobileData == 1;
}
It seems to return the correct result even if I have an active WiFi connection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With