android`FetworkInfo`

时间:2017-02-24 13:49:19

标签: android connectivity networkinfo

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

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的状态?

2 个答案:

答案 0 :(得分:3)

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

您可以阅读此主题以查找最后一个问题。 Android Check if there is WiFi but no internet

答案 1 :(得分:0)

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