android 中判断WiFi是否可用的可靠方法 ,android 是否联网


http://alex-yang-xiansoftware-com.iteye.com/blog/619841

 

 

在一些程序中,需要从网上下载数据,或者通过其他方式对网络产生流量,当wifi不可用时应该提示用户wifi已经不可用了,是否继续,因为如果wifi掉了,那么程序可能采用3G卡或其他的收费的渠道使用网络,会导在不知情时产生大量的上网费用。通过查看android的api可使用下列方法进行判断:

Java代码 复制代码  收藏代码
  1. public static boolean isWiFiActive(Context inContext) {   
  2.         Context context = inContext.getApplicationContext();   
  3.         WifiManager wifiManager = (WifiManager) context   
  4.                 .getSystemService(Context.WIFI_SERVICE);   
  5.         return wifiManager.isWifiEnabled();   
  6.     }  

 

在模拟器上使用这个方法时,可以正确判断wifi是否可用,但是在真机上就判断不出来。wifi是断开的,但是返回的结果true,造成wifi判断不准确。经过尝试可使用如下的方法判断方能正确:

Java代码 复制代码  收藏代码
  1. public static boolean isWiFiActive(Context inContext) {   
  2.         Context context = inContext.getApplicationContext();   
  3.         ConnectivityManager connectivity = (ConnectivityManager) context   
  4.                 .getSystemService(Context.CONNECTIVITY_SERVICE);   
  5.         if (connectivity != null) {   
  6.             NetworkInfo[] info = connectivity.getAllNetworkInfo();   
  7.             if (info != null) {   
  8.                 for (int i = 0; i < info.length; i++) {   
  9.                     if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {   
  10.                         return true;   
  11.                     }   
  12.                 }   
  13.             }   
  14.         }   
  15.         return false;   
  16.     }  

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM