访问网络可用性状态android(Access network availability state android)

编程入门 行业动态 更新时间:2024-10-15 18:27:24
访问网络可用性状态android(Access network availability state android)

我正在开发一个应用程序,我想访问是否有互联网连接。 我可以使用访问网络状态

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

但这只是返回手机是否连接到互联网。 我想知道连接后是否有互联网可用性。 比如,可能是服务器已关闭或互联网不可用。 请让我知道如何做到这一点!

I am developing an application where i want to access whether there is internet connectivity or not. I can access the network state by using

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

But this just returns whether the mobile is connected to internet or not. I want to know if there is internet availability after connecting. Like, may be the server is down or internet not available. Please let me know how to accomplish this!

最满意答案

试试这样,

URL url = new URL("Your URL"); URLConnection conexion = url.openConnection(); conexion.setConnectTimeout(10000); // Don't forget to put a time limit conexion.connect();

超时后(上述示例为10秒),它将超时异常。 因此,您可以使用它来检查Internet访问是否可用。

Try like this,

URL url = new URL("Your URL"); URLConnection conexion = url.openConnection(); conexion.setConnectTimeout(10000); // Don't forget to put a time limit conexion.connect();

After timeout (10 secs for above mentioned example), It will through time out exception. So You can use it to check whether Internet access is available or not.

更多推荐

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

发布评论

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

>www.elefans.com

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