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

查看:47
本文介绍了检测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.

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

推荐答案

ConnectivityManagergetActiveNetworkInfo() 方法返回一个 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上是否有可用的互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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