微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/android/430654.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐