[英]How to disable mobile data connection in android programmatically?
I would like to know if there is any way to disable mobile data connection in android programmatically. 我想知道是否有任何方法可以在Android中以编程方式禁用移动数据连接。 Since there is a class known as WifiManager to handle the wifi 由于存在一个称为WifiManager的类来处理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? 如何在Android中以编程方式禁用它?
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 另外,在AndroidManifest.xml
,您需要添加
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
请参阅ConnectivityManager 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.