如果检测Android设备有互联网连接

编程入门 行业动态 更新时间:2024-10-27 20:35:18
本文介绍了如果检测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; }

(从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设备有互联网连接

本文发布于:2023-11-27 17:01:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:互联网   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!