2017-02-24 146 views
1

我試圖檢查設備是否連接到互聯網。我有以下的實施做Android中的`isConnected()`和`isAvailable()```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沒有互聯網連接的狀態?

+0

你檢查的[文件](https://developer.android.com/reference/android/net/NetworkInfo.html)? – aandis

+0

你做得對。在嘗試建立連接之前,您應該調用'isConnected()' –

+0

@aandis yes我做了'isConnected()' - 表示網絡連接是否存在isAvailable()表示網絡連接是否可能。兩者看起來一樣。需要知道確切的區別和用法 – arjun

回答

2

如果設備連接到網絡,isConnected返回true。 如果設備未連接但網絡可用於連接,則isAvailable返回true,isConnected返回false。

您可以閱讀本主題以查找最後一個問題。 Android Check if there is WiFi but no internet

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

相關問題