如何在android中以编程方式禁用移动数据连接?

时间:2011-08-18 14:13:19

标签: java android connection 3g

我想知道是否有任何方法可以通过编程方式在Android中禁用移动数据连接。由于有一个称为WifiManager的类来处理wifi

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    wifi.setWifiEnabled(false);

是否有任何此类用于处理移动数据连接?如何在android中以编程方式禁用它?

2 个答案:

答案 0 :(得分:0)

请参阅ConnectivityManager

答案 1 :(得分:0)

您可以尝试this,代码如下:

public boolean invokeMethod(String methodName, Object[] args) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[] argsClass = null;
    if (args != null) {
        argsClass = new Class[1];
        argsClass[0] = args.getClass();
    }
    Method method = ownerClass.getMethod(methodName, argsClass);
    return (Boolean)method.invoke(mcm, args);
}

public Object invokeBooleanArgMethod(String methodName, boolean value) throws Exception {
    ConnectivityManager mcm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    Class ownerClass = mcm.getClass();
    Class[]  argsClass = new Class[1];
    argsClass[0] = boolean.class;
    Method method = ownerClass.getMethod(methodName,argsClass);
    return method.invoke(mcm, value);
}

/* use these two method like these */
Object[] arg = null;
try {
    boolean isMobileDataEnable = invokeMethod("getMobileDataEnabled", arg);
    if(!isMobileDataEnable){
        invokeBooleanArgMethod("setMobileDataEnabled", true);
    }
} 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"/>