How to tell if 'Mobile Network Data' is en

2020-01-24 03:30发布

I have an app that I want to be able to use to get a connection status report from a remote query.

I want to know if WiFi is connected, and if data access is enabled over mobile network.

If the WiFi goes out of range I want to know if I can rely on the mobile network.

The problem is that data enabled is always returned as true when I am connected by WiFi, and I can only properly query the mobile network when not connected by WiFi.

all the answers I have seen suggest polling to see what the current connection is, but I want to know if mobile network is available should I need it, even though I might be connected by WiFi at present.

Is there anyway of telling whether mobile network data is enabled without polling to see if is connected?

EDIT

So when connected by WiFi If I go to settings and deselect 'Data Enabled' and then in my app I do this:

 boolean mob_avail = 
 conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isAvailable();

mob_avail is returned as 'true', but I have disabled Mobile Network Data, so I would expect it to be 'false'

If I turn off the WiFi, there is (rightly) no connection as I have disabled mobile network data.

so how do I check if mobile network data is enabled when I am connected by WiFi?

UPDATE

I took a look at getAllNetworkInfo() as suggested in the comments by ss1271

I outputted the info returned about the mobile network under the following 3 conditions

WiFi Off - Mobile Data on

WiFi On - Mobile Data off

WiFi On - Mobile Data on

and got the following results:

With WiFi OFF:

mobile[HSUPA], state: CONNECTED/CONNECTED, reason: unknown, extra: internet, roaming: false, failover: false, isAvailable: true, featureId: -1, userDefault: false

With WiFi On / Mobile OFF

NetworkInfo: type: mobile[HSUPA], state: DISCONNECTED/DISCONNECTED, reason: connectionDisabled, extra: (none), roaming: false, failover: false, isAvailable: true, featureId: -1, userDefault: false

With WiFi On / Mobile On

NetworkInfo: type: mobile[HSPA], state: DISCONNECTED/DISCONNECTED, reason: connectionDisabled, extra: (none), roaming: false, failover: false, isAvailable: true, featureId: -1, userDefault: false

So as you can see isAvailable returned true each time, and state only showed as Disconnected when WiFi was in affect.

CLARIFICATION

I am NOT looking to see if my phone is currently connected by Mobile Network. I AM trying to establish whether or not the user has enabled / disabled Data access over mobile network. They can turn this on and off by going to Settings -> Wireless and Network Settings ->Mobile Network Settings -> Data enabled

17条回答
欢心
2楼-- · 2020-01-24 04:00

Here is a xamarin solution to this problem:

    public static bool IsMobileDataEnabled()
    {
        bool result = false;

        try
        {
            Context context = //get your context here or pass it as a param

            if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr1)
            {
                //Settings comes from the namespace Android.Provider
                result = Settings.Global.GetInt(context.ContentResolver, "mobile_data", 1) == 1;
            }
            else
            {
                result = Settings.Secure.GetInt(context.ContentResolver, "mobile_data", 1) == 1;
            }
        }
        catch (Exception ex)
        {
            //handle exception
        }

        return result;
    }

PS: Make sure you have all the permissions for this code.

查看更多
beautiful°
3楼-- · 2020-01-24 04:00

According to android documentation https://developer.android.com/training/monitoring-device-state/connectivity-monitoring#java

ConnectivityManager cm =
     (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();
查看更多
萌系小妹纸
4楼-- · 2020-01-24 04:03

You must use the ConnectivityManager, and NetworkInfo details can be found here

查看更多
Luminary・发光体
5楼-- · 2020-01-24 04:03

Here is a simple solution from two other answers:

        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return tm.isDataEnabled();

        } else {
            return tm.getSimState() == TelephonyManager.SIM_STATE_READY && tm.getDataState() != TelephonyManager.DATA_DISCONNECTED;
        }
查看更多
够拽才男人
6楼-- · 2020-01-24 04:03
private boolean haveMobileNetworkConnection() {
        boolean haveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {

            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedMobile;
    }

Note: you will need to have permission android.permission.ACCESS_NETWORK_STATE to be able to use this code

查看更多
ら.Afraid
7楼-- · 2020-01-24 04:07

@sNash's function works great. 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.

I updated @snash's function with the above function used. 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;
    }
查看更多
登录 后发表回答