Iiro Krankka
Iiro Krankka

Reputation: 5239

Has the user enabled the mobile data?

I want to get the "Use mobile networks" settings value (true or false). There's a way of knowing if wifi is enabled and it can be done like this:

WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
int state = wm.getWifiState();
boolean pref = state == WifiManager.WIFI_STATE_ENABLED || state == WifiManager.WIFI_STATE_ENABLING;

But how can I do the same check for data?

Upvotes: 3

Views: 1227

Answers (3)

PageNotFound
PageNotFound

Reputation: 2320

You can try this:

public boolean getMobileDataEnabled() throws Exception {
    ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Method method = ownerClass.getMethod("getMobileDataEnabled");
    return (Boolean)method.invoke(mcm);
}

and add the permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Upvotes: 1

Mert
Mert

Reputation: 1363

i hope it helps :)

ConnectivityManager connect = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Boolean isConnected = connect.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();

Upvotes: 1

Josh Pogrob
Josh Pogrob

Reputation: 80

Have you tried using getDataState() from the TelephonyManager class?

TelephonyManager tm = (TelephonyManager)Context.getSystemService (Context.TELEPHONY_SERVICE);
int state = tm.getDataState();
boolean pref = state == TelephonyManager.DATA_CONNECTED;

This should check the state of the data connection.

Upvotes: 0

Related Questions