android 判断网络连接是否可用
2013-11-10 11:46
579 查看
为了提高用户体验,我们在开发 android 应用的过程需要联网获取数据的时候我们首先要做的一步就是:
1.判断当前手机是否打开了网络,
2.打开了网络是否可以上网,
然后再去执行联网逻辑,避免没联网做不必要的工作!
通常情况下,我们是这样判断的
但是这样只完成了第一步,判断网络是否打开,
注意:打开并不代表就可以上网,
观察发现 NetworkInfo 有一个方法:
NetworkInfo.isAvailable()
官方的解释是
他列举了几种网络已连接但不可以上网的情况,
所以我们这样改改就好了:
1.判断当前手机是否打开了网络,
2.打开了网络是否可以上网,
然后再去执行联网逻辑,避免没联网做不必要的工作!
通常情况下,我们是这样判断的
public static boolean isNetAvailable(Context context) { ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (connectManager.getActiveNetworkInfo() != null); }
但是这样只完成了第一步,判断网络是否打开,
注意:打开并不代表就可以上网,
观察发现 NetworkInfo 有一个方法:
NetworkInfo.isAvailable()
官方的解释是
Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include The device is out of the coverage area for any network of this type. The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled. The device's radio is turned off, e.g., because airplane mode is enabled. Returns: true if the network is available, false otherwise
他列举了几种网络已连接但不可以上网的情况,
所以我们这样改改就好了:
public static boolean isNetAvailable(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); return (info != null && info.isAvailable()); }
相关文章推荐
- Android判断网络连接是否可用【从新浪云搬运】
- Android中判断网络连接是否可用及监控网络状态
- Android判断网络连接是否可用,WiFi、移动数据是否打开等
- Android中判断网络连接是否可用及监控网络状态
- Android-判断网络连接是否可用及监控网络状态
- Android 中判断网络连接和GPS是否可用及HTTPCLIENT使用
- Android中判断网络连接是否可用及监控网络状态
- Android中判断网络连接是否可用
- Android判断网络连接是否可用(代码)
- Android中判断网络连接是否可用及监控网络状态
- Android中判断网络连接是否可用及监控网络状态
- Android判断网络连接是否可用(代码)
- Android中判断网络连接是否可用及监控网络状态
- Android中判断网络连接是否可用
- Android中判断网络连接是否可用及监控网络状态
- Android中判断网络连接是否可用及监控网络状态
- Android开发_判断网络连接是否可用
- Android判断网络连接是否可用(代码)
- Android中判断网络连接是否可用
- [Android]判断网络连接是否可用