检查活动的互联网连接 Android [英] Check for Active internet connection Android

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

问题描述

我正在尝试在我的应用程序中编写一个部分来区分活动 Wifi 连接和实际的互联网连接.使用连接管理器找出是否有活动的 Wifi 连接非常简单,但是每次我尝试测试是否可以在 Wifi 连接但没有互联网连接时连接到网站时,我都会陷入无限循环.
我曾尝试 ping 谷歌,但结果是一样的:

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) {
    e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;

我也试过这个代码:

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

但我无法让 isReachable 工作.

but I could not get isReachable to work.

推荐答案

它对我有用:

验证网络可用性:

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

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

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