android 中判斷WiFi是否可用的可靠方法

在一些程序中,須要從網上下載數據,或者經過其餘方式對網絡產生流量,當wifi不可用時應該提示用戶wifi已經不可用了,是否繼續,由於若是wifi掉了,那麼程序可能採用3G卡或其餘的收費的渠道使用網絡,會導在不知情時產生大量的上網費用。經過查看android的api可以使用下列方法進行判斷: javascript

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

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.     }  
相關文章
相關標籤/搜索