How to reliably detect an Internet connection at Android phone wake up
<p>I have an App that relies on Internet connection at startup, and I am able to detect that ok with the code below.</p>

<p>However when the phone has been idle for some time and I unlock it and start my app it does not find the connection immediately and I have to re-start the app again to get success.</p>

<p>I have tried waiting in a thread and retrying the code below again with no success too.</p>

<p>Any ideas would be appreciated, thank you. </p>

<p><strong>Code</strong> </p>

<pre><code>    // check Network/Internet connection
    public boolean isOnline() {

    try {
        ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;

        cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI")) {
                if (ni.isConnected()) {
                    haveConnectedWifi = true;
                }
            }
            if (ni.getTypeName().equalsIgnoreCase("MOBILE")) {
                if (ni.isConnected()) {
                    haveConnectedMobile = true;
                }
            }
        }
        return haveConnectedWifi || haveConnectedMobile;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }
    return false;
}
</code></pre>
