android 控制移动网络开关

5.0之前,这样就行:


if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) {
ITelephony iTelephony = ITelephony.Stub
.asInterface(ServiceManager
.getService(Context.TELEPHONY_SERVICE));
if (toggle) {
iTelephony.enableDataConnectivity();
} else {
iTelephony.disableDataConnectivity();
}
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO
&& Build.VERSION.SDK_INT < 21) {


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, toggle);


5.0之后,网络提供的方法:


TelephonyManager telephonyService = (TelephonyManager) cxt
.getSystemService(Context.TELEPHONY_SERVICE);
try {
Method setMobileDataEnabledMethod = telephonyService.getClass()
.getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataEnabledMethod) {
setMobileDataEnabledMethod.invoke(telephonyService,
mobileDataEnabled);
}
} catch (Exception e) {
Log.e("InstallActivity", "Errot setting"
+ ((InvocationTargetException) e).getTargetException()
+ telephonyService);
}


需要加入 权限


只有系统APP才好使,我没测试,不符合需求,经各方面查找,发现360流量卫士通过实现了这个功能,正在研究

你可能感兴趣的:(Android)