棒棒糖版本的支持需要一个新的系统级别权限
android.permission.MODIFY_PHONE_STATE
才能正常工作。
private static boolean setMobileConnectionEnabled(Context context, boolean enabled)
{
try{
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD){
final TelephonyManager telMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
final Method getITelephony = telMgr.getClass().getDeclaredMethod("getITelephony");
getITelephony.setAccessible(true);
final Object objITelephony = getITelephony.invoke(telMgr);
final Method toggleDataConnectivity = objITelephony.getClass()
.getDeclaredMethod(enabled ? "enableDataConnectivity" : "disableDataConnectivity");
toggleDataConnectivity.setAccessible(true);
toggleDataConnectivity.invoke(objITelephony);
}
else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Field serviceField = connMgr.getClass().getDeclaredField("mService");
serviceField.setAccessible(true);
final Object connService = serviceField.get(connMgr);
try{
final Method setMobileDataEnabled = connService.getClass()
.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabled.setAccessible(true);
setMobileDataEnabled.invoke(connService, Boolean.valueOf(enabled));
}
catch(NoSuchMethodException e){
final Method setMobileDataEnabled = connService.getClass()
.getDeclaredMethod("setMobileDataEnabled", String.class, Boolean.TYPE);
setMobileDataEnabled.setAccessible(true);
setMobileDataEnabled.invoke(connService, context.getPackageName(), Boolean.valueOf(enabled));
}
}
else{
final TelephonyManager telMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
final Method setDataEnabled = telMgr.getClass().getDeclaredMethod("setDataEnabled", Boolean.TYPE);
setDataEnabled.setAccessible(true);
setDataEnabled.invoke(telMgr, Boolean.valueOf(enabled));
}
return true;
}
catch(NoSuchFieldException e){
Log.e(TAG, "setMobileConnectionEnabled", e);
}
catch(IllegalAccessException e){
Log.e(TAG, "setMobileConnectionEnabled", e);
}
catch(IllegalArgumentException e){
Log.e(TAG, "setMobileConnectionEnabled", e);
}
catch(NoSuchMethodException e){
Log.e(TAG, "setMobileConnectionEnabled", e);
}
catch(InvocationTargetException e){
Log.e(TAG, "setMobileConnectionEnabled", e);
}
return false;
}
需要权限。
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>