Kalai Selvan.G
Kalai Selvan.G

Reputation: 482

How to check server connection is available or not in android

Testing of Network Connection can be done by following method:

 public boolean isNetworkAvailable() 
{
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected())
    {
        return true;
    }
    return false;
}

But i don't know how to check the server connection.I had followed this method

public boolean isConnectedToServer(String url, long timeout) {
try{
    URL myUrl = new URL(url);
    URLConnection connection = myUrl.openConnection();
    connection.setConnectTimetout(timeout);
    connection.connect();
    return true;
} catch (Exception e) {
    // Handle your exceptions
    return false;
}

}

it doesn't works....Any Ideas Guys!!

Upvotes: 2

Views: 7824

Answers (2)

Dhina k
Dhina k

Reputation: 1489

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;
}

}

and also add intent permission in your manifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

you can check a server connection is available or not using isReachable():

netAddress address = InetAddress.getByName(HOST_NAME);
boolean  reachable = address.isReachable(timeout);

and by using runtime:

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping www.google.com");

Upvotes: 2

Related Questions