androiddataservice3g-network

How to turn off 3G data connection programmatically in android?


I want to Enable/Disable 3G and other Data connections separately.Is it possible to access 3G individually?That means if the user selects the option 3G, then Enable/Disable 3G data connection only.And if the user selects the option Data Services, enable/disable data connections except 3G.Is it possible? I tried the following methods

enableDataConnectivity();
and
disableDataConnectivity();
of
TelephonyManager

But i think these methods turn off/on all data services in whole.I want to access 3G separately.

How to do this?


Solution

  • This code sample should work for android phones running gingerbread and higher:

    private void setMobileDataEnabled(Context context, boolean enabled) 
    {
       final ConnectivityManager conman = (ConnectivityManager)    
       final ConnectivityManager conman = (ConnectivityManager)
       context.getSystemService(Context.CONNECTIVITY_SERVICE);
       final Class conmanClass = Class.forName(conman.getClass().getName());
       final 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);
       setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
    }
    

    This also requires the following permission.

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