检测 Android 上是否有可用的 Internet 连接 [英] Detect whether there is an Internet connection available on Android

查看:38
本文介绍了检测 Android 上是否有可用的 Internet 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

  1. 如何让上面的代码片段工作?
  2. 我如何在在线文档中找到我需要的信息?
  3. 您能否为此类检测提出一种更好的方法?

推荐答案

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

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" />

在您的 android 清单中.

in your android manifest.

请注意,拥有活动的网络接口并不能保证特定的网络服务可用.网络问题、服务器停机、低信号、强制门户、内容过滤器等都会阻止您的应用程序到达服务器.例如,在您收到来自 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 上是否有可用的 Internet 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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