I have to implement a function that controls the presence of the internet connection, I need to know precisely if you can browse and not know if you are connected or not to the wifi or data.
There may be cases where you are connected to a network but you can not browse, for example when you connect to an open wifi network (eg Mc Donalds) but to navigate you need to login, the connection available but you are not able to browse.
In that case I would be enough to take advantage of the set timeout (but it is never considered).
I tried to implement different functions but I can not get the desired result, for example:
public boolean checkConnection() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
boolean response;
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.it");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(1000);
conn.connect();
response = conn.getResponseCode() == 200;
conn.disconnect();
} catch (Exception e) {
response = false;
}
} else {
response = false;
}
return response;
}
Another function:
public boolean isInternetAvailable(String address, int port, int timeoutMs) {
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress(address, port);
sock.connect(sockaddr, timeoutMs);
sock.close();
return true;
} catch (IOException e) { return false; } }
This functions never takes the timeout into consideration.
How i can solve my problem ??
**************** EDIT 1 ****************
I'm testing the code on a tablet connected to a network via wifi, through the firewall I blocked all connections in order to simulate the situation described in the ever question. Using the codes suggested to me you notice that the timeout value is never respected, the application goes in exception:
Exception: java.net.UnknownHostException: Unable to resolve host "www.google.com": No address associated with hostname.
The real problem is that all these functions take too long to tell me that there is no connectivity, I would need a function that responds in 1/2 sec