android – 检测如果没有互联网连接

我有一个代码来确定是否有网络连接:

    ConnectivityManager cm = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected()) 
    {
        // There is an internet connection
    }

但如果有网络连接而没有互联网,这是没用的.我必须ping一个网站并等待响应或超时以确定互联网连接:

    URL sourceUrl;
    try {
        sourceUrl = new URL("http://www.google.com");
        URLConnection Connection = sourceUrl.openConnection();
        Connection.setConnectTimeout(500);
        Connection.connect();
    } catch (MalformedURLException e) {
        // Todo Auto-generated catch block
        e.printstacktrace();

        // no Internet
    } catch (IOException e) {
        // Todo Auto-generated catch block
        e.printstacktrace();

        // no Internet
    }

但这是一个缓慢的检测.我应该学习一种快速方法来检测它.

提前致谢.

最佳答案
尝试以下方法来检测不同类型的连接:

private boolean haveNetworkConnection(Context context)
{
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) Your_Activity_Name.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    // or if function is out side of your Activity then you need context of your Activity
    // and code will be as following
    // (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo)
    {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        {
            if (ni.isConnected())
            {
                haveConnectedWifi = true;
                System.out.println("WIFI CONNECTION AVAILABLE");
            } else
            {
                System.out.println("WIFI CONNECTION NOT AVAILABLE");
            }
        }
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        {
            if (ni.isConnected())
            {
                haveConnectedMobile = true;
                System.out.println("MOBILE INTERNET CONNECTION AVAILABLE");
            } else
            {
                System.out.println("MOBILE INTERNET CONNECTION NOT AVAILABLE");
            }
        }
    }
    return haveConnectedWifi || haveConnectedMobile;
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...