检测Android应用程序中的Internet连接?

时间:2012-12-17 05:37:08

标签: android android-networking

我有以下方法,它将检查设备中的Internet连接:

public static boolean checkInternetConnection(Context context) {
    ConnectivityManager connectivityManager = 
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager.getActiveNetworkInfo() != null
            && connectivityManager.getActiveNetworkInfo().isAvailable()
            && connectivityManager.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }

}

但过了一会儿,我发现这种方法只检查网络连接;就像设备连接到路由器并且路由器处于开启但没有互联网可用时,此方法返回true。

那么如何知道是否存在实际的互联网?

4 个答案:

答案 0 :(得分:4)

那么'实际的互联网'是什么?能够在任何给定时间连接到Internet上任何可能的主机吗?有点难以测试,不是吗?尝试连接到知名服务器(谷歌,美国国家航空航天局,您所在国家/地区的顶级提供商主页),如果有效,您可能拥有“实际互联网”。

答案 1 :(得分:1)

我看到的唯一方法就是尝试连接到谷歌这样的网站,如果你得到结果,那么你就可以确定它,否则就没有网络活动。

答案 2 :(得分:0)

试试这个功能......

public static Boolean checknetwork(Context mContext) 
    {

        NetworkInfo info = ((ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (info == null || !info.isConnected()) 
        {

            return false;
        }
        if (info.isRoaming()) 
        {
            // here is the roaming option you can change it if you want to
            // disable internet while roaming, just return false
            return true;
        }

        return true;

    }

答案 3 :(得分:0)