Search code examples
javaandroidwifimanager

how to programmatically determine if android is connected to wifi?


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?


Solution

  • Send a "ping" if you want to call it that. If the connection completes, you know you are still connected. If you get an IOException or a NullPointerException, then you probably timed out and are not connected anymore.

    try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
            urlConnect.setConnectTimeout(1000);
            urlConnect.getContent();
            System.out.println("Connection established.");
        } catch (NullPointerException np) {
            np.printStackTrace();
        } catch (IOException io) {
            io.printStackTrace();
        }