禁用移动网络编程
我开发一个应用程序中,用户可以启用按钮点击/禁用移动网络。我用Google搜索关于这个,但我只得到飞行模式的解决方案。在飞行模式下,WI-FI和蓝牙也被禁用。我不想让他们通过使用飞行模式的概念来禁用。我想唯一的移动网络被禁用。什么是实现它的可能的方式亲语法?
I'm developing an app in which user can enable/disable mobile network on button click. I googled regarding this, but I get the solution of Airplane mode only. In airplane mode, WI-FI and Bluetooth are also disabled. I don't want them to disable by using airplane mode concept. I want only mobile network to be disabled. What are the possible way to implement it pro-grammatically?
低于code为禁用/启用移动网络使用。
Use below code for Disable/Enable Mobile Network..
private void setMobileConnectionEnabled(Context context, boolean enabled) {
final ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class mClass = Class.forName(mConnectivityManager.getClass().getName());
final Field mField = mClass.getDeclaredField("mService");
mField.setAccessible(true);
final Object mObject = mField.get(mConnectivityManager);
final Class mConnectivityManagerClass = Class.forName(mObject.getClass().getName());
final Method setMobileDataEnabledMethod = mConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
setMobileDataEnabledMethod.invoke(mObject, enabled);
}
您必须在 menifest.xml
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
如果你想关闭整个网络,那么你可以做的禁用/启用飞行模式
If you want Disable whole network then you can do Disable/Enable AirplaneMode