0

I want to toggle off the Network data through programming. I have tried Below Code but is only switching off the network data not doing the toggle off in the Mobile Data in Setting.

try {
    final ConnectivityManager conman = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final java.lang.reflect.Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField.get(conman);
    final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);
    // (true) to enable 3G; (false) to disable it.
    setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
} catch (Exception e) {
    e.printStackTrace();
}
PageNotFound
  • 2,320
  • 2
  • 23
  • 34
abhi
  • 154
  • 16

1 Answers1

0

Use this code to toggle off mobile network:

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

public void setMobileDataEnabled(boolean enabled) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    ownerClass.getMethod("setMobileDataEnabled",boolean.class).invoke(mcm, enabled);
}

try {
    boolean isMobileDataEnable = getMobileDataEnabled();
    if (isMobileDataEnabled) {
        setMobileDataEnabled(!isMobileDataEnable);
    }
} catch (Exception e) {
    e.printStackTrace();
}

In AndroidManifest.xml add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
PageNotFound
  • 2,320
  • 2
  • 23
  • 34