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);
Related videos on Youtube
![JiTHiN](https://i.stack.imgur.com/T0tix.jpg?s=256&g=1)
Comments
-
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 almost 12 yearsWhat is the result of
e.getMessage()
on theInvocationTargetException
? How about the enclosed exception? -
David Wasser almost 12 yearsWhat device are you running this on and what version of Android OS is installed on that device.
-
JiTHiN almost 12 yearsI'm running it on a Samsung Galaxy S and the Android OS is 2.2
-
-
Bucks almost 12 yearswhat parameter need to send data enable and data disable?
-
mcacorner over 11 yearsI got java.lang.reflect.InvocationTargetException error after run this code.
-
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 over 11 yearsThanks for reply but, I have already add permission and I am using Android 2.2
-
Tobias Moe Thorstensen over 11 yearsThat 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 about 11 yearsFor android versions less than 2.3 we can use the java reflection method to enable/disable data connection. Refer stackoverflow.com/questions/11662978/….
-
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 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 over 10 yearsRunning this in AsyncTask does not throw background ANR.
-
who-aditya-nawandar over 10 yearsCan someone tell me what other changes are required with using the code... like namespaces that need to be imported, etc...
-
SoulRayder about 10 yearsI 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 about 10 yearsConfirmed 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 almost 9 yearsFor line
Class.forName(conman.getClass().getName());
I have got a java.lang.ClassNotFoundException. How to solve it ? -
Tushar Monirul over 8 yearsWhat is the phone is dual sim?
-
ransh about 8 yearsDoes it turn off the radio connection (GSM) too ?
-
Minion about 5 yearsjava.lang.NoSuchMethodException: setMobileDataEnabled [boolean]
-
Tobias Moe Thorstensen about 5 years@PrakashSharma The method or Api might have been deprecated. PLease consider that this post is from 2012.