aaa SA
aaa SA

Reputation: 323

android why get different wifi connect state

I hope to make a getConnectState() boolean function. I use two way below. I don't know why in some situation there are different result. Like when I am turning on WiFi, sometimes the first one will return true, but second one return false; In this situation, the WiFi is on opening but not already connect, I hope I can get false. Can anyone explain to me why the first one function tell me the WiFi is enabled.

    WifiManager wifiManager=(WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    if(wifiManager.getWifiState()==WifiManager.WIFI_STATE_ENABLED)
        return true;
    else
        return false;

and

    ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networInfo = conManager.getActiveNetworkInfo(); 
    if (networInfo == null || !networInfo.isAvailable()) { 
        return false;
    }
    return true;

Upvotes: 0

Views: 167

Answers (1)

kelvin langford
kelvin langford

Reputation: 76

WifiManager.WIFI_STATE_ENABLED

Only checks if the wifi connection is enabled, and does not check if it is connected. You can check the state of the connection by using:

ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networInfo = conManager.getActiveNetworkInfo();
if(networInfo.getState()==State.CONNECTED)

and if you want to make sure that the network is using WIFI you can use

networInfo.getType()==connection.TYPE_WIFI

Upvotes: 2

Related Questions