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.
How can I do this without slowing down the app with an infinite loop?
private boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
} catch (Exception exc) {
return false;
}
}