如何从源头code更改Android设备的网络状态? [英] How to change the network state of device from source code in Android?
本文介绍了如何从源头code更改Android设备的网络状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图改变从源头code设备的网络状态。
我观察到有授予的申请,即改变网络状态的权限,CHANGE_NETWORK_STATE。
I am trying to change the network state of the device from the source code.
I observed that there is a permission to grant to the applications for changing the network state i.e., CHANGE_NETWORK_STATE.
但我无法找到任何例子或者code,可以改变一个设备的网络状态。
But I am not able to find any example or code that can change the network state of a device.
请让我知道如果任何人知道或有一个例子来更改设备的网络状态。
Please let me know if anyone knows or have an example to change the network state of a device.
问候,
SSuman185
Regards,
SSuman185
推荐答案
这code的工作。我把它从这里。
This code is working. I got it from here.
private void setMobileDataEnabled(Context context, boolean enabled) {
try {
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final 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);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
}
这篇关于如何从源头code更改Android设备的网络状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文