2

网络连接测试可以通过以下方法进行:

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

}

它不起作用....任何想法伙计们!

4

2 回答 2

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");
于 2012-03-31T11:16:44.367 回答
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" />
于 2015-05-27T09:29:59.277 回答