【问题标题】:How to check server connection is available or not in android如何在android中检查服务器连接是否可用
【发布时间】:2012-03-31 11:04:34
【问题描述】:

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

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

}

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

【问题讨论】:

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


    【解决方案1】:

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

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

    并通过使用运行时:

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

    【讨论】:

    • 获取 java.net.UnknownHostException
    • 您使用的是哪个主机名?如果您有 www.google.com 之类的网址,请尝试使用第二个选项
    • selvan,你知道 ping 命令做了什么。这两个选项告诉你主机(服务器)是否可用
    • Gud..Its to Check for Server availability.fine Imran..如果服务器宕机了,那时我们该怎么办?
    • 当服务器连接不可用时,然后做你想做的事?我不知道你的要求。通过这个你只能确定服务器连接是否可用作为你的问题
    【解决方案2】:
    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" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多