Android API call to determine user setting "Data Enabled"
My program tries to detect whether a mobile network is available at a certain location开发者_JAVA技巧.
The issue is that when I don't have a data connection it doesn't mean the network is not there... it depends on the user preferences.
There are APIs available for NetworkInfo.isAvailable()
, and for user settings such as whether user is roaming and roaming is enabled or whether AirplaneMode is on.
My problem is that I can't figure out whether the user has data services disabled under Settings/WirelessNetworks/MobileNetworks.
Sounds like a trivial problem but I haven't found an API call.
In your activity:
boolean mobileDataAllowed = Settings.Secure.getInt(getContentResolver(), "mobile_data", 1) == 1;
Source: https://github.com/yanchenko/quick-settings/blob/master/src/com/bwx/bequick/handlers/MobileDataSettingHandler2.java#L123
I know above answer worked for OP. But in few devices I found it returns true even if data is disabled. So I found one alternate solution which is in Android API.
getDataState() method of TelephonyManager will be very useful.
Below function returns false when cellular data is disabled otherwise true.
private boolean checkMobileDataIsEnabled(Context context){
boolean mobileYN = false;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
TelephonyManager tel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
// if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1)
// {
// mobileYN = Settings.Global.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
// }
// else{
// mobileYN = Settings.Secure.getInt(context.getContentResolver(), "mobile_data", 0) == 1;
// }
int dataState = tel.getDataState();
Log.v(TAG,"tel.getDataState() : "+ dataState);
if(dataState != TelephonyManager.DATA_DISCONNECTED){
mobileYN = true;
}
}
return mobileYN;
}
精彩评论