I am using isConnected() method to test Internet is working or not, However, When Mobile data is on but net is not working (happens when travelling) or Wifi is on but not connected to internet, the method returns true and my app crashes.
I did some finding and found that I need to ping Google also so I tried using internetConnectionAvailable(1000). Even if Internet is working fine, this method sometimes return false. Can anybody help me with a better solution?
//Check device has Internet connection
public boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else {
//Custom Toast method
showToast("Unable to connect to Internet !");
return false;
}
}
//ping google and test internet connection
private boolean internetConnectionAvailable(int timeOut) {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
@Override
public InetAddress call() {
try {
return InetAddress.getByName("www.google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
Log.e("Google",String.valueOf(inetAddress));
return inetAddress!=null && !inetAddress.equals("");
}