Here we go again,
Hint: this post will be just a wrap up to what you can find here.
Unfortunately, the data-connection enable/disable APIs are not exposed to the user, So we'll access them using JAVA reflection.
Starting from API level 8 (platform 2.2) we can use the following snippet:
final ConnectivityManager conman =
(ConnectivityManager) context.getSystemService(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);
// (true) to enable 3G; (false) to disable it.
setMobileDataEnabledMethod.invoke(iConnectivityManager, true);
We need to add the following permission to the manifest file
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
Hint: the previous piece of code was tested on SAMSUNG GALAXY SII API level 9(platform 2.3).
Ok, now I'll post another snippet that I got it working on the emulator for APIs levels prior to (8):
Method dataConnSwitchmethod;
Class telephonyManagerClass;
Object ITelephonyStub;
Class ITelephonyClass;
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if(telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED){
isEnabled = true;
}else{
isEnabled = false;
}
telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
getITelephonyMethod.setAccessible(true);
ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());
if (isEnabled) {
// if you want to disable it.
dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("disableDataConnectivity");
} else {
// if you want to enable it.
dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("enableDataConnectivity");
}
dataConnSwitchmethod.setAccessible(true);
dataConnSwitchmethod.invoke(ITelephonyStub);
That's it, don't hesitate to comment, to share your knowledge and to correct me.
Android: Enable/Disable 3G programmatically