7

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?

Community
  • 1
  • 1
Flynn
  • 5,903
  • 7
  • 38
  • 55

3 Answers3

25

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. ;-)

ahodder
  • 11,353
  • 14
  • 71
  • 114
  • your down vote may have been because you specify timeout as a long, but .setConnectTimeout (which you miss-spelled) only accepts an int value. – Evan R. Sep 20 '12 at 18:22
  • @levi, I'm not sure what you are getting at, so my answer would have to be don't do it? – ahodder Sep 17 '14 at 20:32
  • I mean, this method should be run background. If not it will trigger NetworkOnMainThreadException – levi Sep 17 '14 at 20:41
  • @levi. I see what you are saying, but in terms of the question it was not relevant to point out. – ahodder Sep 17 '14 at 22:05
  • @levi I'm not sure I follow you. You want me to update the answer to include the fact that that exception may be thrown or make a note? Regardless, your comment will suffice to all future viewers. – ahodder Sep 17 '14 at 23:28
  • If i want to show a message (alertdialog,toast, etc.) how can i do it using this code? I tried it but i can only make it show the message when there's conection to the server, hope someone can tell me – Armando Jan 03 '18 at 06:48
3

You can try

InetAddress.getByName(host).isReachable(timeOut)
Oguz Ozkeroglu
  • 3,025
  • 3
  • 38
  • 64
1
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();
            }
Ferdiyan Syah
  • 404
  • 4
  • 6