android - 检测是否没有互联网连接

标签 android wifi

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

    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 - 检测是否没有互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11718367/

相关文章:

android - android调试器丢失怎么办?

java - 在 Android 应用程序中自动打开 Wifi 热点

iOS/来自驱动程序的 rssi 事件太频繁了..?

android - android连接wifi网络,密码错误返回

android - 摩托罗拉 Droid 3 相机应用程序杀死后台应用程序

android - 如何为谷歌地图标记设置 id 以识别选择了哪个?

java - 尝试在空对象引用上调用虚拟方法 'android.os.Looper android.content.Context.getMainLooper()'

android - WifiManager.getConfiguredNetworks 总是返回空列表

android - 停止重复计时器android

android - MotionLayout - 日志中恼人的调试错误 : "no widget for <view id> (<view type>)"