Enable/disable data connection in android programmatically

72,408

Solution 1

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"/>

Solution 2

@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);
Share:
72,408

Related videos on Youtube

JiTHiN
Author by

JiTHiN

#SOreadytohelp

Updated on April 11, 2020

Comments

  • JiTHiN
    JiTHiN about 4 years

    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.

    • Greyson
      Greyson almost 12 years
      What is the result of e.getMessage() on the InvocationTargetException? How about the enclosed exception?
    • David Wasser
      David Wasser almost 12 years
      What device are you running this on and what version of Android OS is installed on that device.
    • JiTHiN
      JiTHiN almost 12 years
      I'm running it on a Samsung Galaxy S and the Android OS is 2.2
  • Bucks
    Bucks almost 12 years
    what parameter need to send data enable and data disable?
  • mcacorner
    mcacorner over 11 years
    I got java.lang.reflect.InvocationTargetException error after run this code.
  • Tobias Moe Thorstensen
    Tobias Moe Thorstensen over 11 years
    @ReferenceNotFound Are you sure you added the permission? 11 other people or more got i working, including me.
  • mcacorner
    mcacorner over 11 years
    Thanks for reply but, I have already add permission and I am using Android 2.2
  • Tobias Moe Thorstensen
    Tobias Moe Thorstensen over 11 years
    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!
  • JiTHiN
    JiTHiN about 11 years
    For android versions less than 2.3 we can use the java reflection method to enable/disable data connection. Refer stackoverflow.com/questions/11662978/….
  • Vigbyor
    Vigbyor over 10 years
    +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 ?
  • Rajaraman Subramanian
    Rajaraman Subramanian over 10 years
    @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 Subramanian
    Rajaraman Subramanian over 10 years
    Running this in AsyncTask does not throw background ANR.
  • who-aditya-nawandar
    who-aditya-nawandar over 10 years
    Can someone tell me what other changes are required with using the code... like namespaces that need to be imported, etc...
  • SoulRayder
    SoulRayder about 10 years
    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?
  • Telmo Marques
    Telmo Marques about 10 years
    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?
  • GuyOlivier
    GuyOlivier almost 9 years
    For line Class.forName(conman.getClass().getName()); I have got a java.lang.ClassNotFoundException. How to solve it ?
  • Tushar Monirul
    Tushar Monirul over 8 years
    What is the phone is dual sim?
  • ransh
    ransh about 8 years
    Does it turn off the radio connection (GSM) too ?
  • Minion
    Minion about 5 years
    java.lang.NoSuchMethodException: setMobileDataEnabled [boolean]
  • Tobias Moe Thorstensen
    Tobias Moe Thorstensen about 5 years
    @PrakashSharma The method or Api might have been deprecated. PLease consider that this post is from 2012.