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.
Asked
Active
Viewed 7,006 times
4
-
http://stackoverflow.com/questions/11555366/enable-disable-data-connection-in-android-programmatically – Anudeep Sep 16 '15 at 09:45
-
Can you please explain "turning on mobile data on dual sim phones?" – Waseem Ahmad Naeem Feb 10 '18 at 12:22
-
Now data enable/disable is restricted, and not possible from code! – Apr 08 '22 at 09:20
1 Answers
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

Community
- 1
- 1

Abdul Aleem
- 679
- 8
- 31
-
Could you please explain turning on data on dual sim phones? – Waseem Ahmad Naeem Feb 10 '18 at 12:22