Best Pratice maintaining SocketConnection while network (Mobile -> Wifi) changes
<p>I have an android app which connects to a server using a socket connection which is kept open while the app is active. If the phone gets inactive (lock screen) or the user presses the home button, the application closes the socket connection and reopens it if the app becomes visible again.</p>

<p>This Pattern works fine on most of the android phones we have (about 15 devices), but the Motorola Milestone, Defy, SE Xperia Arc and the LG Optimus One need very long (>10 secs) to detect if a Wifi is available after and connect to it. So to wait for the best network connection I use the following code (before opening the socket to the server):</p>

<pre><code>public static boolean waitNetworkConnection(Context context, int retries) {
    ConnectivityManager cm = (ConnectivityManager) 
                       context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = getNetworkToTest(cm);

    if (ni == null || !ni.isConnected()) {
        // sleep a short while to allow system to switch connecting networks.
        Tools.sleep(1000);
        int counter = 0;
        while (counter &lt; retries &amp;&amp; (ni == null || (ni.isAvailable() &amp;&amp; 
               !ni.isConnected()))) {
            Tools.sleep(500);
            ni = getNetworkToTest(cm);
            counter++;
        }
    }

    return (cm.getActiveNetworkInfo() != null &amp;&amp; 
            cm.getActiveNetworkInfo().isConnected());
}
</code></pre>

<p>and this method (use by the one above) to get the connection to test, which prefers a Wifi-Connection if one (not necessary connected) is available:</p>

<pre><code>private static NetworkInfo getNetworkToTest(ConnectivityManager cm) {
    NetworkInfo[] nis = cm.getAllNetworkInfo();
    NetworkInfo ni = cm.getActiveNetworkInfo();

    for (int i = 0; i &lt; nis.length; i++) {
        if (nis[i].getType() == 1 /* Wifi */ &amp;&amp; nis[i].isAvailable()) {
            ni = nis[i];
            return(ni);
        }
    }
    return(ni);
}
</code></pre>

<p>This works fine for most of the devices, but for the mentioned ones this very often fails and this method tells me to use a mobile network connection and the device switches the connection type while I open a socket connection which leads to a SocketException with a very generic error message so I'm unable to determine if the socket connection is caused by this issue or because of some other network error.</p>

<p>Simply doing a retry doesn't fix this either, as this breaks the handling for the other network errors because it then takes very long to detect a socket timeout (because it is checked twice).</p>

<p>Has anyone else ran into this problem (very slowing connect to Wifi) and has a solution for this?</p>
