可以通过以下方法测试网络连接:
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;
}
}
它不起作用......有什么想法吗?
最佳答案
您可以使用 isReachable()
检查服务器连接是否可用:
netAddress address = InetAddress.getByName(HOST_NAME);
boolean reachable = address.isReachable(timeout);
并使用运行时:
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("ping www.google.com");
关于android - 如何在android中检查服务器连接是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9955325/