4

I'm still relatively new to Android app development but im trying to create an app which toggles internet connectivity upon the click of a button within the app. is there any way to actually do this, as i havent found any resources online on how to do this. ive included all user permissions that might be of help in the app's manifest but cant seem to make it work. Thanks.

Sapiens
  • 41
  • 1
  • 3

1 Answers1

2

This code sample should work for android phones. For Android 2.3 and above:

private void setMobileDataEnabled(Context context, boolean enabled) {
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);}

also requires the following permission

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

Please follow below URL for more clarification.

EDIT:

1: Enable/disable data connection in android programmatically

2: How can i turn off 3G/Data programmatically on Android?

Community
  • 1
  • 1
Abdul Aleem
  • 679
  • 8
  • 31