7

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
prepbgg
  • 3,564
  • 10
  • 39
  • 51

3 Answers3

3

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;
        }
akshay7692
  • 601
  • 1
  • 8
  • 19
muscatmat
  • 31
  • 1
2

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.

Mikhail
  • 844
  • 8
  • 18
0

Please look at this code : (code of one of my published apps on the play store)

private static boolean isAPNEnabled(Context paramContext) {
    try {
        NetworkInfo networkInfo = ((ConnectivityManager) paramContext.getSystemService("connectivity")).getActiveNetworkInfo();
        return networkInfo.isConnected();
    } catch (Exception e) {
        return false;
    }
}
Mathieu de Brito
  • 2,536
  • 2
  • 26
  • 30
  • Thanks for the suggestion; however, this code returns true if either WiFi or a Mobile data connection is available. I am trying to detect specifically whether Mobile data is enabled (regardless of whether there is a WiFi connection). – prepbgg Sep 10 '12 at 18:45