发布于 2016-02-23 21:38:32 | 263 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要介绍了Android编程判断网络连接是否可用的方法,实例分析了Android判定网络连接的相关技巧与实现步骤,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务