Reputation: 6181
So I have a method that checks if the device is connected to the internet based on this one
It works ok, but in a couple of cases I find that although the phone shows being connected to the internet, it still does not have access to my server. What I am really looking to do it check connection to my specific URL.
How could I implement that?
Upvotes: 7
Views: 24676
Reputation: 404
Runtime runtime = Runtime.getRuntime();
Process proc;
try {
proc = runtime.exec("ping -c 1"+ (String) getText(R.string.Server));
proc.waitFor();
int exit = proc.exitValue();
if (exit == 0) { // normal exit
} else { // abnormal exit, so decide that the server is not
// reachable
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // other servers, for example
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 1
Reputation: 11439
You could do something like:
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}
This will attempt to connect to your server's URL and if it fails, you obviously don't have a connection. ;-)
Upvotes: 25
Reputation: 3057
You can try
InetAddress.getByName(host).isReachable(timeOut)
Upvotes: 3