当前位置: 移动技术网 > 移动技术>移动开发>Android > Android编程判断网络连接是否可用的方法

Android编程判断网络连接是否可用的方法

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了android编程判断网络连接是否可用的方法。分享给大家供大家参考,具体如下:

为了提高用户体验,我们在开发 android 应用的过程需要联网获取数据的时候我们首先要做的一步就是:

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程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网