重置网络配置 android,重置Android移动网络信号?

棒棒糖支持需要新的系统级别权限android.permission.MODIFY_PHONE_STATE才能工作.

private static boolean setMobileConnectionEnabled(Context context, boolean enabled)

{

try{

// Requires: android.permission.CHANGE_NETWORK_STATE

if(Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD){

// pre-Gingerbread sucks!

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

}

// Requires: android.permission.CHANGE_NETWORK_STATE

else if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){

final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

// Gingerbread to KitKat inclusive

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){

// Support for CyanogenMod 11+

final Method setMobileDataEnabled = connService.getClass()

.getDeclaredMethod("setMobileDataEnabled", String.class, Boolean.TYPE);

setMobileDataEnabled.setAccessible(true);

setMobileDataEnabled.invoke(connService, context.getPackageName(), Boolean.valueOf(enabled));

}

}

// Requires: android.permission.MODIFY_PHONE_STATE (System only, here for completions sake)

else{

// Lollipop and into the Future!

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;

}

需要权限.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值