加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Android 判断 网络连接 Internet访问 工具类

发布时间:2020-12-15 03:13:18 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 前言 利用Android自带的ConnectivityManager类 有时候连上了wifi,但这个wifi是上不了网的,我们可以通过ping www.baidu.com来判断是否可以上网 也可

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

前言

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

Android 判断 网络连接

判断网络是否已经连接

// 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;

}

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

// 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;
}

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

疑惑点

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

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读