如何在android中检查服务器连接是否可用

时间:2012-03-31 11:04:34

标签: android android-layout android-emulator android-networking

网络连接的测试可以通过以下方法完成:

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

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

但我不知道如何检查服务器连接。我已经遵循了这个方法

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

}

它不起作用......任何想法的人!!

2 个答案:

答案 0 :(得分:2)

您可以使用isReachable()检查服务器连接是否可用:

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

并使用运行时:

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

答案 1 :(得分:0)

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

}

并在清单中添加意图权限

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