Detect broken internet connection whenever the application is running
<p>I'm already using the code below to detect if the user is connected to the internet at the application's splash screen, but I need to detect this whenever the user is in a specific activity. Imagine you are using turn-by-turn navigation and you depend on internet connection, so you must detect a broken internet connection when it happens. </p>

<p>How can I do this without slowing down the app with an infinite loop?</p>

<pre><code>private boolean isOnline(Context context) {
    try {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = cm.getActiveNetworkInfo();

        return (networkInfo != null &amp;&amp; networkInfo.isConnected());
    } catch (Exception exc) {
        return false;
    }
}
</code></pre>
