Android(安卓)通过代码实现控制数据网络的开关(仅适用于5.0以上)
16lz
2022-05-12
Android 5.0以前使用ConnectivityManager通过反射两个方法setMobileDataEnabled和getMobileDataEnabled来控制移动网络开和关。
Android 5.0以后使用TelephonyMananger类通过反射获取setDataEnabled和getDataEnabled类完成操作。
注意:需要使用系统权限:android:sharedUserId=”android.uid.system”。系统需要root
//适应Android5.0+
public void setMobileDataState(Context context, boolean enabled) { TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try { Method setDataEnabled = telephonyService.getClass().getDeclaredMethod("setDataEnabled",boolean.class); if (null != setDataEnabled) { setDataEnabled.invoke(telephonyService, enabled); } } catch (Exception e) { e.printStackTrace(); }}public boolean getMobileDataState(Context context) { TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); try { Method getDataEnabled = telephonyService.getClass().getDeclaredMethod("getDataEnabled"); if (null != getDataEnabled) { return (Boolean) getDataEnabled.invoke(telephonyService); } } catch (Exception e) { e.printStackTrace(); } return false;}
/** 别忘了添加权限 **/
更多相关文章
- 好用的Android(安卓)Studio插件
- 使用模拟器运行应用
- Android侧滑菜单DrawerLayout的使用
- Android(安卓)7.0 后拍照和相册选择
- Android(安卓)ART 垃圾回收 机制&算法
- android:windowSoftInputMode属性使用
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用