Enable/disable data connection in android programmatically
Asked Answered
P

2

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.

Pathology answered 19/7, 2012 at 6:50 Comment(3)
What is the result of e.getMessage() on the InvocationTargetException? How about the enclosed exception?Brittenybrittingham
What device are you running this on and what version of Android OS is installed on that device.Rihana
I'm running it on a Samsung Galaxy S and the Android OS is 2.2Pathology
A
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"/>
Alroy answered 19/7, 2012 at 6:57 Comment(17)
what parameter need to send data enable and data disable?Seductive
I got java.lang.reflect.InvocationTargetException error after run this code.Amerce
@ReferenceNotFound Are you sure you added the permission? 11 other people or more got i working, including me.Alroy
Thanks for reply but, I have already add permission and I am using Android 2.2Amerce
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!Alroy
For android versions less than 2.3 we can use the java reflection method to enable/disable data connection. Refer #11663478.Pathology
+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 ?Restriction
@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?Schramm
Running this in AsyncTask does not throw background ANR.Schramm
Can someone tell me what other changes are required with using the code... like namespaces that need to be imported, etc...Garton
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?Foolish
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?Exciseman
For line Class.forName(conman.getClass().getName()); I have got a java.lang.ClassNotFoundException. How to solve it ?Dewittdewlap
What is the phone is dual sim?Makeweight
Does it turn off the radio connection (GSM) too ?Gobble
java.lang.NoSuchMethodException: setMobileDataEnabled [boolean]Spur
@PrakashSharma The method or Api might have been deprecated. PLease consider that this post is from 2012.Alroy
I
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);
Ingratiating answered 20/4, 2014 at 11:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.