检查活动的Internet连接的Andr​​oid [英] Check for Active internet connection Android

查看:129
本文介绍了检查活动的Internet连接的Andr​​oid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行,所以我想写我的应用程序的一部分,将在Active WiFi连接,并且与互联网的实际连接区分。找出是否存在有效的无线连接使用的连接管理器但是每次我尝试测试,如果我可以连接到一个网站时,无线连接,但没有互联网连接我结束了在一个无限pretty的简单循环。
我试图平谷歌然而,这最终会以同样的方式:

OK so I am trying to write a part in my app that will differentiate between an Active Wifi connection and an actual connection to the internet. Finding out if there is an active Wifi connection is pretty simple using the connection manager however every time I try to test if I can connect to a website when the Wifi is connected but there is no internet connection I end up in an infinite loop.
I have tried to ping google however this ends up the same way:

Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
    int returnVal = 5;
    try {
        returnVal = p1.waitFor();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    boolean reachable = (returnVal==0);
    return reachable;

我也试过这个code:

I also tried this code:

if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{    }
else
{    }

但我无法得到isReachable工作。非常感谢你的帮助!

but I could not get isReachable to work. Thank you so much for your help!

推荐答案

它确实为我的作品:

要验证网络可用性:

private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}

要检查网络连接:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

这篇关于检查活动的Internet连接的Andr​​oid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆