此代码示例应该适用于运行姜饼及更高版本的 android 手机:
private void setMobileDataEnabled(Context context, boolean enabled)
{
final ConnectivityManager conman = (ConnectivityManager)
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);
}
这也需要以下许可。
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>