Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether Android "Mobile data" is on

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?

like image 723
prepbgg Avatar asked Sep 10 '12 13:09

prepbgg


3 Answers

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;
        }
like image 188
muscatmat Avatar answered Nov 05 '22 05:11

muscatmat


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;
like image 37
Venu Gandhe Avatar answered Sep 22 '22 18:09

Venu Gandhe


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.

like image 2
Mikhail Avatar answered Nov 05 '22 05:11

Mikhail