如何使用Android实现WIFI和GPRS网络的切换

  介绍

小编给大家分享一下如何使用Android实现WIFI和GPRS网络的切换,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获、下面让我们一起去了解一下吧!

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

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

& lt; uses-permission  android: name=癮ndroid.permission.ACCESS_WIFI_STATE",/比;   & lt; uses-permission  android: name=癮ndroid.permission.ACCESS_NETWORK_STATE",/比;   & lt; uses-permission  android: name=癮ndroid.permission.CHANGE_WIFI_STATE",/比;   & lt; uses-permission  android: name=癮ndroid.permission.CHANGE_NETWORK_STATE",/在

<强> 1,切换WIFI网络

public  static  void  toggleWiFi (Context 上下文,boolean 启用),{   ,WifiManager  wm =, (WifiManager), context.getSystemService (Context.WIFI_SERVICE);   ,wm.setWifiEnabled(启用);   以前,}

<强> 2,切换GPRS网络

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

public  static  void  toggleMobileData (Context 上下文,boolean 启用),{   ,ConnectivityManager  conMgr =, (ConnectivityManager), context.getSystemService (Context.CONNECTIVITY_SERVICE);   ,   ,Class<?祝辞,conMgrClass =,零,,//,ConnectivityManager类   ,Field  conMgrField =,零,,//,ConnectivityManager类中的字段   ,Object  iConMgr =,零,,//,IConnectivityManager类的引用   ,Class<?祝辞,iConMgrClass =,零,,//,IConnectivityManager类   ,Method  setMobileDataEnabledMethod =,零,,//,setMobileDataEnabled方法   ,   ,try  {   ,//取得ConnectivityManager类=,,conMgrClass  forname (conMgr.getClass () . getname ());   ,//取得ConnectivityManager类中的对象mService=,,conMgrField  conMgrClass.getDeclaredField (“mService");   ,//设置mService可访问   ,conMgrField.setAccessible(真正的);   ,//取得mService的实例化类IConnectivityManager=,,iConMgr  conMgrField.get (conMgr);   ,//取得IConnectivityManager类=,,iConMgrClass  forname (iConMgr.getClass () . getname ());   ,//取得IConnectivityManager类中的setMobileDataEnabled(布尔)方法=,,setMobileDataEnabledMethod  iConMgrClass.getDeclaredMethod (“setMobileDataEnabled",, Boolean.TYPE);   ,//设置setMobileDataEnabled方法可访问   ,setMobileDataEnabledMethod.setAccessible(真正的);   ,//调用setMobileDataEnabled方法   ,setMobileDataEnabledMethod.invoke (iConMgr,启用);   ,}   ,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网络的切换