How to tell if 'Mobile Network Data' is enabled or disabled (even when connected by WiFi)?
The following code will tell you if "mobile data" is enabled or not, regardless of whether or not there is a mobile data connection active at the moment or whether or not wifi is enabled/active or not. This code only works on Android 2.3 (Gingerbread) and later. Actually this code also works on earlier versions of Android as well ;-)
boolean mobileDataEnabled = false; // Assume disabled
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
Class cmClass = Class.forName(cm.getClass().getName());
Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
method.setAccessible(true); // Make the method callable
// get the setting for "mobile data"
mobileDataEnabled = (Boolean)method.invoke(cm);
} catch (Exception e) {
// Some problem accessible private API
// TODO do whatever error handling you want here
}
Note: you will need to have permission android.permission.ACCESS_NETWORK_STATE
to be able to use this code.
I've upgraded Allesio's answer. Settings.Secure's mobile_data int has moved to Settings.Global since 4.2.2.
Try This code when you want to know if mobile network is enabled even when wifi is enabled and connected.
Updated to check if SIM Card is available. Thanks for pointing out murat.
boolean mobileYN = false;
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
{
mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
}
else{
mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 1) == 1;
}
}
One way is to check whether the user has mobile data activated in the Settings, which most likely will be used if wifi goes off. This works (tested), and it doesn't use reflection, although it uses an hidden value in the API:
boolean mobileDataAllowed = Settings.Secure.getInt(getContentResolver(), "mobile_data", 1) == 1;
Depending on the API, you need to check Settings.Global instead of Settings.Secure, as pointed out by @user1444325.
Source: Android API call to determine user setting "Data Enabled"