`
yangwei0915
  • 浏览: 460274 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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

阅读更多

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

public static boolean isWiFiActive(Context inContext) {
		Context context = inContext.getApplicationContext();
		WifiManager wifiManager = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		return wifiManager.isWifiEnabled();
	}

 

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

public static boolean isWiFiActive(Context inContext) {
		Context context = inContext.getApplicationContext();
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
						return true;
					}
				}
			}
		}
		return false;
	}

 

分享到:
评论
3 楼 harvin 2014-07-09  
yangwei0915 写道
可以转载!

谢谢。
2 楼 yangwei0915 2014-05-13  
可以转载!
1 楼 harvin 2014-03-25  
受教了,感谢博主。另外,我能转载吗?

相关推荐

Global site tag (gtag.js) - Google Analytics