如果要用android程序来实现wifi的开启和关闭,是一件十分简单的事,使用WifiManager就可以实现对android wifi接口的控制,开启和关闭wifi都是仅需要两行代码。但如果你想通过代码来实现对gsm、gprs或者3G等移动网络接口控制的话,则不是那么容易了,因为在android开发者文档里并没有明确的方法来实现的,通过查看android的源代码可以知道,源代码是通过ConnectivityManager.setMobileDataEnabled方法来实现移动网络中的使用数据包选项的启用和禁用的,不过android官方刻意地把这个方法隐藏了 ,是通过把方法定义为private类型来对外禁用的,也就是说只有系统级的应用才能调用setMobileDataEnabled方法来控制无线和网络中的移动网络接口。

只要巧用java中的反射就可以实现调用到ConnectivityManager类中的setMobileDataEnabled方法,从而实现用程序来启用和禁用移动网络中的使用数据包选项,达到开启和关闭gprs或者3g移动网络的目的。


接下来直接粘代码吧:

01private void setMobileDataEnabled(Context context, booleanenabled) {
02final String TAG = "setMobileDataEnabled";
03final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
04Class conmanClass;
05try{
06conmanClass = Class.forName(conman.getClass().getName());
07final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
08iConnectivityManagerField.setAccessible(true);
09final Object iConnectivityManager = iConnectivityManagerField.get(conman);
10final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
11final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
12setMobileDataEnabledMethod.setAccessible(true);
13
14setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
15} catch(ClassNotFoundException e) {
16// TODO Auto-generated catch block
17Log.d(TAG, "ClassNotFoundException");
18} catch(NoSuchFieldException e) {
19Log.d(TAG, "NoSuchFieldException");
20} catch(IllegalArgumentException e) {
21Log.d(TAG, "IllegalArgumentException");
22} catch(IllegalAccessException e) {
23Log.d(TAG, "IllegalAccessException");
24} catch(NoSuchMethodException e) {
25Log.d(TAG, "NoSuchMethodException");
26} catch(InvocationTargetException e) {
27Log.d(TAG, "InvocationTargetException");
28}finally{
29
30}
31
32}