我需要知道我的设备有互联网连接或不。我发现很多的答案,如:
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; }
(从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("www.google").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; }
当然,您也可以替换 www.google 网址为你想连接到任何其他的服务器,或者你知道一个服务器具有良好正常运行时间。
Of course you can substitute the www.google URL for any other server you want to connect to, or a server you know has a good uptime.
由于托尼卓也指出,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设备有互联网连接
发布评论