如果检测Android设备有互联网连接 [英] Detect if Android device has Internet connection

查看:151
本文介绍了如果检测Android设备有互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道我的设备有互联网连接或不。我发现很多的答案,如:

I need to tell if my device has Internet connection or not. I found many answers like:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
         = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

(从<一个拍摄href="http://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android">Detect是否有互联网连接在Android 。)

(Taken from Detect whether there is an Internet connection available on Android.)

但是,这是不对的,例如,如果我的连接到没有上网无线网络,此方法将返回true ... 有没有办法告诉如果设备有互联网连接,而不是如果只是连接到些什么呢?

But this is not right, for example if I'm connected to a wireless network which doesn't have Internet access, this method will return true… Is there a way to tell if the device has Internet connection and not if it is only connected to something?

推荐答案

你是对的。 c您的$ C $如果有网络连接所提供只检查。 最好的方法,以检查是否有可用的Internet连接是尝试连接 通过HTTP已知的服务器。

You are right. The code you've provided only checks if there is a network connection. The best way to check if there is an active Internet connection is to try and connect to a known server via http.

public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

当然,您也可以替换 http://www.google.com 网​​址为你想连接到任何其他的服务器,或者你知道一个服务器具有良好正常运行时间。

Of course you can substitute the http://www.google.com URL for any other server you want to connect to, or a server you know has a good uptime.

由于托尼卓也指出,<一个href="http://stackoverflow.com/questions/6493517/android-detect-if-device-has-internet-connection/6493572#comment25721630_6493572">this下面发表评论,请务必不要运行在主线程此code,否则你会得到一个NetworkOnMainThread异常(在安卓3.0或更高版本)。使用的AsyncTask或Runnable接口来代替。

As Tony Cho also pointed out in this comment below, make sure you don't run this code on the main thread, otherwise you'll get a NetworkOnMainThread exception (in Android 3.0 or later). Use an AsyncTask or Runnable instead.

这篇关于如果检测Android设备有互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆