1

我正在尝试检查设备是否已连接到互联网。我有以下实现来做到这一点

public static boolean isConnectedToNetwork(Context context) {
  ConnectivityManager connectivityManager =
    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

NetworkInfo提供了两种方法isConnected()isAvailable(). 我应该使用哪一个,它们之间有什么区别。

有没有办法在Wifi没有互联网连接的情况下检测设备连接的状态?

4

2 回答 2

4

如果设备连接到网络,isConnected 返回 true。如果设备未连接但网络可连接,isAvailable 返回 true,isConnected 返回 false。

您可以阅读本主题以找到您的最后一个问题。 Android 检查是否有 WiFi 但没有互联网

于 2017-02-24T13:56:54.993 回答
2
isConnected()

Indicates whether network connectivity exists and it is possible to establish connections and pass data.

- Always call this before attempting to perform data transactions.

isAvailable()

Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include

- The device is out of the coverage area for any network of this type.

- The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled.

- The device's radio is turned off, e.g., because airplane mode is enabled.

Reference Link

于 2017-02-24T16:20:15.313 回答