Android怎么实现WIFI和GPRS网络的切换

本篇内容介绍了“Android怎么实现WIFI和GPRS网络的切换”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

定襄网站制作公司哪家好,找创新互联建站!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联建站于2013年成立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联建站

在项目的开发中因为要使用到WIFI和GPRS网络的切换,因此就研究了一下通过代码打开WIFI和GPRS的工作。

无论是切换WIFI还是切换GPRS网络都需要设置相应的权限,所以需要在AndroidManifest.xml文件中加入以下几行代码。

1、切换WIFI网络

public static void toggleWiFi(Context context, boolean enabled) { WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wm.setWifiEnabled(enabled); }

2、切换GPRS网络

由于Android没有提供直接切换GPRS网络的方法,通过查看系统源码发现,系统是调用IConnectivityManager类中的setMobileDataEnabled(boolean)方法来设置GPRS网络的,由于方法不可见,只能采用反射来调用,代码如下。

public static void toggleMobileData(Context context, boolean enabled) { ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); Class conMgrClass = null; // ConnectivityManager类 Field conMgrField = null; // ConnectivityManager类中的字段 Object iConMgr = null; // IConnectivityManager类的引用 Class iConMgrClass = null; // IConnectivityManager类 Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法 try { // 取得ConnectivityManager类 conMgrClass = Class.forName(conMgr.getClass().getName()); // 取得ConnectivityManager类中的对象mService conMgrField = conMgrClass.getDeclaredField("mService"); // 设置mService可访问 conMgrField.setAccessible(true); // 取得mService的实例化类IConnectivityManager iConMgr = conMgrField.get(conMgr); // 取得IConnectivityManager类 iConMgrClass = Class.forName(iConMgr.getClass().getName()); // 取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法 setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); // 设置setMobileDataEnabled方法可访问 setMobileDataEnabledMethod.setAccessible(true); // 调用setMobileDataEnabled方法 setMobileDataEnabledMethod.invoke(iConMgr, enabled); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }

根据以上所写就可以做到WIFI网络和GPRS网络的切换了。

“Android怎么实现WIFI和GPRS网络的切换”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站标题:Android怎么实现WIFI和GPRS网络的切换
浏览地址:http://ybzwz.com/article/gojspc.html