80,351
社区成员
发帖
与我相关
我的任务
分享
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;
}
权限: <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
注意要系统签名才行
特别注意, 从来没有开过网络的机器, 如果是支持多卡的手机要先手动开过网络, 不然不知道你选哪张卡