Android API call to determine user setting “Data Enabled”

依然范特西╮ 提交于 2019-11-27 03:33:03

问题


My program tries to detect whether a mobile network is available at a certain location.

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.


回答1:


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




回答2:


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;
    }


来源:https://stackoverflow.com/questions/6591774/android-api-call-to-determine-user-setting-data-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!