广告
返回顶部
首页 > 资讯 > 移动开发 >Android中判断网络连接状态的方法
  • 130
分享到

Android中判断网络连接状态的方法

连接网络连接方法Android 2022-06-06 09:06:48 130人浏览 泡泡鱼
摘要

App判断用户是否联网是很普遍的需求,实现思路大概有下面几种 利用Android自带的ConnectivityManager类 有时候连上了wifi,但这个wifi是上

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中判断网络连接是否可用及监控网络状态Android使用URL读取网络资源的方法Android检测url地址是否可达的两种方法


--结束END--

本文标题: Android中判断网络连接状态的方法

本文链接: https://www.lsjlt.com/news/25689.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作