2012-02-07 203 views
5

所以我有一个检查,如果设备连接到互联网的方法based on this one安卓:检查连接到服务器

它的工作原理确定,但在几个案例我发现,虽然手机显示连接到互联网,它仍然无法访问我的服务器。我真的想要做的是检查连接到我的特定URL。

我该怎么实现?

回答

23

你可以这样做:

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

这将尝试连接到您的服务器的URL,如果失败,你显然不具备的连接。 ;-)

+0

您的投票可能是因为您指定超时为long,但.setConnectTimeout(您错过拼写)只接受一个int值。 – 2012-09-20 18:22:44

+0

你知道NetworkOnMainThreadException吗?.. – levi 2014-09-17 15:34:22

+0

@levi,我不知道你在做什么,所以我的答案不得不这样做吗? – AedonEtLIRA 2014-09-17 20:32:42

2

您可以尝试

InetAddress.getByName(host).isReachable(timeOut) 
0
Runtime runtime = Runtime.getRuntime(); 
      Process proc; 
      try { 
       proc = runtime.exec("ping -c 1"+ (String) getText(R.string.Server)); 
       proc.waitFor(); 
       int exit = proc.exitValue(); 
       if (exit == 0) { // normal exit 


       } else { // abnormal exit, so decide that the server is not 
          // reachable 


       } 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } // other servers, for example 
      catch (InterruptedException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      }