48

I want to enable/disable the data connection programmatically. I've used the following code:

void enableInternet(boolean yes)
{
    ConnectivityManager iMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Method iMthd = null;
    try {
        iMthd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
        } catch (Exception e) {
               } 
    iMthd.setAccessible(false);

    if(yes)
     {

                try {
                    iMthd.invoke(iMgr, true);
                    Toast.makeText(getApplicationContext(), "Data connection Enabled", Toast.LENGTH_SHORT).show();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                     dataButton.setChecked(false);
                     Toast.makeText(getApplicationContext(), "IllegalArgumentException", Toast.LENGTH_SHORT).show();

                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "IllegalAccessException", Toast.LENGTH_SHORT).show();

                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                     dataButton.setChecked(false);
                     Toast.makeText(getApplicationContext(), "InvocationTargetException", Toast.LENGTH_SHORT).show();

                }

     }
    else
     {
        try {
            iMthd.invoke(iMgr, true);
            Toast.makeText(getApplicationContext(), "Data connection Disabled", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                   dataButton.setChecked(true);
                Toast.makeText(getApplicationContext(), "Error Disabling Data connection", Toast.LENGTH_SHORT).show();
                                    }
     }
}

It's working without any errors in the emulator but, I'm getting "InvocationTargetException" when I try to run it on a real device. I'm using API level 8 to build the application.

dfeuer
  • 44,398
  • 3
  • 56
  • 155
JiTHiN
  • 6,348
  • 5
  • 39
  • 67

2 Answers2

90

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

private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    final ConnectivityManager conman = (ConnectivityManager)  context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
    connectivityManagerField.setAccessible(true);
    final Object connectivityManager = connectivityManagerField.get(conman);
    final Class connectivityManagerClass =  Class.forName(connectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
}

Dont forget to add this line to your manifest file

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
msysmilu
  • 1,846
  • 20
  • 21
Tobias Moe Thorstensen
  • 8,395
  • 12
  • 66
  • 132
  • what parameter need to send data enable and data disable? – Bucks Sep 05 '12 at 10:59
  • 1
    I got java.lang.reflect.InvocationTargetException error after run this code. – mcacorner Jan 09 '13 at 11:36
  • @ReferenceNotFound Are you sure you added the permission? 11 other people or more got i working, including me. – Tobias Moe Thorstensen Jan 09 '13 at 11:43
  • Thanks for reply but, I have already add permission and I am using Android 2.2 – mcacorner Jan 10 '13 at 06:44
  • That is why it doesn't work. This workaround only works for Gingerbread and higher, which means you have to be on Android 2.3 or higher. Sorry! – Tobias Moe Thorstensen Jan 10 '13 at 07:44
  • 9
    For android versions less than 2.3 we can use the java reflection method to enable/disable data connection. Refer http://stackoverflow.com/questions/11662978/how-to-provide-option-to-select-wi-fi-or-gprs-for-network-connectivity-in-android. – JiTHiN Apr 23 '13 at 10:59
  • +1, your method worked very well for me. Thanks, is there anyway I can set GPS on Off programmatically same as you did Internet on/off programmatically like above ? – Vigbyor Sep 30 '13 at 11:16
  • @TobiasMoeThorstensen I tried adding this code in the AppWidgetProvider OnReceive method but I am getting **W/ActivityManager(444): Killing ProcessRecord{a6bdce00 1809:com.rajaraman.quicksettings/u0a10064}: background ANR** Do I have to run this in a thread to avoid ANR? – Rajaraman Oct 25 '13 at 15:47
  • Running this in AsyncTask does not throw background ANR. – Rajaraman Oct 25 '13 at 17:15
  • Can someone tell me what other changes are required with using the code... like namespaces that need to be imported, etc... – whoadityanawandar Nov 12 '13 at 09:42
  • I have a theoretical doubt. Is the above code an example of the usage of *reflection*? If not, then what do you call such a method employed here as? – SoulRayder Apr 29 '14 at 09:42
  • Confirmed working on 4.4.2. However, lines 4-7 seem redundant as we already have a ConnectivityManager object. Is there any meaning to this? – Telmo Marques Jun 01 '14 at 00:07
  • For line `Class.forName(conman.getClass().getName());` I have got a java.lang.ClassNotFoundException. How to solve it ? – GuyOlivier Jul 28 '15 at 10:21
  • What is the phone is dual sim? – Tushar Monirul Nov 04 '15 at 12:31
  • Does it turn off the radio connection (GSM) too ? – ransh May 22 '16 at 21:22
  • java.lang.NoSuchMethodException: setMobileDataEnabled [boolean] – Minion May 10 '19 at 10:27
  • @PrakashSharma The method or Api might have been deprecated. PLease consider that this post is from 2012. – Tobias Moe Thorstensen May 10 '19 at 10:28
1

@riHaN JiTHiN your program works fine for 2.3 and above, But it needs a small change in 'else' statement:

else
     {
        try {
            iMthd.invoke(iMgr, true);

the 'true' should be changed to 'false'

iMthd.invoke(iMgr, false);
chiastic-security
  • 19,689
  • 3
  • 33
  • 62