前言

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

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

文章链接 http://blog.csdn.net/never_cxb/article/details/47658257 转载请注明出处

Android 判断 网络连接

判断网络是否已经连接

// check all network connect, WIFI or mobilepublic 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;}

利用 ping 判断 Internet 能够 请求成功

Note

有时候连上了网络, 但却上不去外网

// network available cannot ensure Internet is availablepublic 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

其他方案 模拟 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); }

疑惑点

stackoverflow 也是这么写的 type.equalsIgnoreCase(“WIFI”)
我疑惑这个 “WIFI” 为什么是硬编码

如果文章对您有帮助,请赏注彩票钱^=^

更多相关文章

  1. android apk 程序签名
  2. 一篇文章看明白 Android(安卓)系统启动时都干了什么
  3. 安卓入门教程(ps参考网络大部分教程,其中有些内容为搬砖。)
  4. android7.0适配
  5. Android(安卓)HttpURLConnection及HttpClient对比
  6. android 网络下载图片 效率对比
  7. Flutter开始干系列-一个完整的登录实践
  8. Android(安卓)网络连接:Volley(齐射)之简单使用
  9. android连网详解

随机推荐

  1. 我是如何自学成为程序员的
  2. Android中的dex分包
  3. Android(安卓)Eclipse下工程移植到Androi
  4. Android状态栏提醒(Notification,Notific
  5. Android(安卓)禁止ViewPager的滑动效果
  6. Android之rild进程启动源码分析
  7. Andy Rubin:手机不应该是你的助手
  8. Android中Calendar与Date的区别以及消除
  9. Android(安卓)中 如何利用am input 命令
  10. android 应用类APP开发小结——android G