Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Check connection to server

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?

like image 743
Flynn Avatar asked Feb 07 '12 16:02

Flynn


People also ask

What is a server in android?

A Mobile Web Server is software designed for modern-day smartphones to host personal web servers, through the use of open sourced software, such as, i-jetty, an open source software, based on jetty. I-jetty is an open source web container, serving Java-based web content such as, servlets and JSPs.


3 Answers

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

like image 146
ahodder Avatar answered Oct 19 '22 19:10

ahodder


You can try

InetAddress.getByName(host).isReachable(timeOut)
like image 28
Oguz Ozkeroglu Avatar answered Oct 19 '22 17:10

Oguz Ozkeroglu


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();
            }
like image 43
Ferdiyan Syah Avatar answered Oct 19 '22 19:10

Ferdiyan Syah