检测Android上是否有可用的互联网连接

编程入门 行业动态 更新时间:2024-10-28 00:17:51
本文介绍了检测Android上是否有可用的互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能的重复:如何在 Android 上检查互联网访问?InetAddress 永不超时

我需要检测 Android 设备是否连接到互联网.

I need to detect whether the Android device is connected to the Internet.

NetworkInfo 类提供了一个听起来很完美的非静态方法 isAvailable().

The NetworkInfo class provides a non-static method isAvailable() that sounds perfect.

问题在于:

NetworkInfo ni = new NetworkInfo(); if (!ni.isAvailable()) { // do something }

抛出这个错误:

The constructor NetworkInfo is not visible.

可以肯定的是,还有另一个返回 NetworkInfo 对象的类.但我不知道是哪个.

Safe bet is there is another class that returns a NetworkInfo object. But I don't know which.

  • 如何使上述代码片段起作用?
  • 我怎样才能在在线文档中找到我需要的信息?
  • 您能否为此类检测提出更好的方法?
  • 推荐答案

    ConnectivityManager 的 getActiveNetworkInfo() 方法返回一个 NetworkInfo 实例,表示它可以找到的第一个连接的网络接口或 null 如果没有连接任何接口.检查此方法是否返回 null 应该足以判断互联网连接是否可用.

    The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

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

    您还需要:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    在你的安卓清单中.

    请注意,拥有活动网络接口并不能保证特定的网络服务可用.网络问题、服务器停机、低信号、强制门户、内容过滤器等都会阻止您的应用程序到达服务器.例如,在您收到 Twitter 服务的有效响应之前,您无法确定您的应用是否可以访问 Twitter.

    Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

    更多推荐

    检测Android上是否有可用的互联网连接

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

    发布评论

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

    >www.elefans.com

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