how to programmatically determine if android is connected to wifi?

kptkev picture kptkev · Jan 10, 2013 · Viewed 9.7k times · Source

I'm trying to setup a test for automation on a new android app that I'm developing but having a bit of trouble with one of the apis

The problem i'm facing is I want to start the test AFTER wifi has a connection, not when its in the connecting state. I have tried two solutions but had no luck and test seems to start before my android device is fully connected (no x on the wifi bars)

wifiManager.setWifiEnabled(state);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
while (wifiInfo.getSSID() == null) {
    Log.i("WifiStatus", "Here I am");
    Thread.sleep(Time.ONE_SECOND);
    wifiInfo = wifiManager.getConnectionInfo();

This is my first implementation trying to get the SSID to determine if connection has been established. but the test still starts before a full connection has been made and fails the setup.

ConnectivityManager connManager = 
    (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

wifiManager.setWifiEnabled(state);
while (!networkInfo.isConnected()) {
    Log.i("WifiStatus", "Here I am");
    Thread.sleep(Time.ONE_SECOND);
    networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}

The second implementation i'm using connectivity manager instead and using isConnected().

Does anyone have another method I can possibly check to determine if the device has fully established a connection with wifi?

Answer

Felix picture Felix · Jan 11, 2013

Instead of getting the networkinfo manually... try getting the 'currently active' network and checking if that is the wifi. Note: If it is null that means that no network is connected... so it replaces the isConnected call.

ConnectivityManager connManager = 
    (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo current = connManager.getActiveNetworkInfo();
boolean isWifi = current != null && current.getType() == ConnectivityManager.TYPE_WIFI;