如何通过编程关闭移动网络数据
问题描述:
我想通过编程关闭网络数据。我尝试过“以下代码”,但只关闭了未设置“移动数据”设置中的切换关闭的网络数据。如何通过编程关闭移动网络数据
try {
final ConnectivityManager conman = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final java.lang.reflect.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);
// (true) to enable 3G; (false) to disable it.
setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
} catch (Exception e) {
e.printStackTrace();
}
答
使用此代码关闭同时移动网络:
public boolean getMobileDataEnabled() throws Exception {
ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Class ownerClass = mcm.getClass();
Method method = ownerClass.getMethod("getMobileDataEnabled");
return (Boolean)method.invoke(mcm);
}
public void setMobileDataEnabled(boolean enabled) throws Exception {
ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Class ownerClass = mcm.getClass();
ownerClass.getMethod("setMobileDataEnabled",boolean.class).invoke(mcm, enabled);
}
try {
boolean isMobileDataEnable = getMobileDataEnabled();
if (isMobileDataEnabled) {
setMobileDataEnabled(!isMobileDataEnable);
}
} catch (Exception e) {
e.printStackTrace();
}
在AndroidManifest.xml
添加
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
它不工作 – abhi 2014-09-20 08:37:27