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

android– 检测如果没有互联网连接,第1张

概述我有一个代码来确定是否有网络连接: ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (n

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

    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 – 检测如果没有互联网连接全部内容,希望文章能够帮你解决android – 检测如果没有互联网连接所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/web/1140043.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-31
下一篇2022-05-31

发表评论

登录后才能评论

评论列表(0条)

    保存