android 控制移动网络开关

本文介绍了如何在不同的Android版本中实现数据连接的开启与关闭,包括针对5.0之前的版本使用ITelephony接口,5.0及之后版本使用TelephonyManager的方法。需要注意的是,这些操作需要系统级权限,并且需要加入MODIFY_PHONE_STATE权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}


需要加入<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> 权限


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值