There is no official way to do this. However, it can be achieved unofficially with reflection.
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);
}
Note that both of these are unofficial and may no longer work. No more proof of this kind of thing breaking should be needed, as the 2.2 and below method broke on 2.3.
Surround the code with try/catch blocks
In the Manifest, add the following permission:
There is no official way to do this. However, it can be achieved unofficially with reflection.
For Android 2.3 and above:
This also requires the following permission.
For Android 2.2 and below:
This required the following permission:
Note that both of these are unofficial and may no longer work. No more proof of this kind of thing breaking should be needed, as the 2.2 and below method broke on 2.3.
I'm still on 2.1, so this solution works for me.
But you need also to include MODIFY_PHONE_STATE permision.
Full code (with a toogle button) 2.1:
Manifest.xml
activity_turn3_gon_off.xml