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

前端之家收集整理的这篇文章主要介绍了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;
}
原文链接:https://www.f2er.com/android/430654.html

猜你在找的Android相关文章