开发者

How to disable mobile data connection in android programmatically?

开发者 https://www.devze.com 2023-03-28 20:08 出处:网络
I would like to know if there is any way to disable mobile data connection in android pr开发者_如何学编程ogrammatically. Since there is a class known as WifiManager to handle the wifi

I would like to know if there is any way to disable mobile data connection in android pr开发者_如何学编程ogrammatically. Since there is a class known as WifiManager to handle the wifi

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

Is there are any such class for handling mobile data connection? How to disable it programmatically in android?


See ConnectivityManager.


You can try this and the code is below:

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

Also, in AndroidManifest.xml, you need to add

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消