发布于 2016-02-24 03:04:21 | 222 次阅读 | 评论: 0 | 来源: 网友投递

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

Android移动端操作系统

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


App判断用户是否联网是很普遍的需求,这篇文章主要介绍了Android中判断网络连接状态的方法,感兴趣的朋友可以参考一下

App判断用户是否联网是很普遍的需求,实现思路大概有下面几种

  • 利用Android自带的ConnectivityManager类
  • 有时候连上了wifi,但这个wifi是上不了网的,我们可以通过ping www.baidu.com来判断是否可以上网
  • 也可以利用get请求访问www.baidu.com,如果get请求成功,说明可以上网

1、判断网络是否已经连接


// check all network connect, WIFI or mobile
public static boolean isNetworkAvailable(final Context context) {
  boolean hasWifoCon = false;
  boolean hasMobileCon = false;
 
  ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
  NetworkInfo[] netInfos = cm.getAllNetworkInfo();
  for (NetworkInfo net : netInfos) {
 
    String type = net.getTypeName();
    if (type.equalsIgnoreCase("WIFI")) {
      LevelLogUtils.getInstance().i(tag, "get Wifi connection");
      if (net.isConnected()) {
        hasWifoCon = true;
      }
    }
 
    if (type.equalsIgnoreCase("MOBILE")) {
      LevelLogUtils.getInstance().i(tag, "get Mobile connection");
      if (net.isConnected()) {
        hasMobileCon = true;
      }
    }
  }
  return hasWifoCon || hasMobileCon;
 
}

2、利用 ping 判断 Internet 能够 请求成功
Note:有时候连上了网络, 但却上不去外网


// network available cannot ensure Internet is available
public static boolean isNetWorkAvailable(final Context context) {
  Runtime runtime = Runtime.getRuntime();
  try {
    Process pingProcess = runtime.exec("/system/bin/ping -c 1 www.baidu.com");
    int exitCode = pingProcess.waitFor();
    return (exitCode == 0);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return false;
}

考虑到网络, 我们 ping 了www.baidu.com
国外的话可以 ping 8.8.8.8

3、其他方案 模拟 get 请求

也可以访问网址, 看 get 请求能不能成功


URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
  return new Boolean(true);
}

以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。



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

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