2017-02-24 4 views
1

デバイスがインターネットに接続されているかどうかを確認しようとしています。私はandroid `NetworkInfo`の` isConnected() `と` isAvailable() `の相違点

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はい '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