2010-05-07 66 views
9

如何使用Android服务执行ping回拨?我需要打开一个网页点击按钮,但在后台,去平另一个网址的统计收集。Android服务 - Ping URL

代码片段将是很大的帮助

感谢 克里斯

回答

16

我认为,如果你只是想ping一个网址,你可以使用此代码:如果你想

try { 
    URL url = new URL("http://"+params[0]); 

    HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
    urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION); 
    urlc.setRequestProperty("Connection", "close"); 
    urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds 
    urlc.connect(); 

    if (urlc.getResponseCode() == 200) { 
     Main.Log("getResponseCode == 200"); 
     return new Boolean(true); 
    } 
} catch (MalformedURLException e1) { 
    e1.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

而且,要具有相当于ping的功能,可以在调用之前和之后放置一个System.currentTimeMillis(),并计算差异。

希望帮助

代码片段在here

+0

发现这一直对我很好,除了它总是失败的Android 4的设备。有任何想法吗? – dee 2012-02-10 16:29:33

+9

您需要将呼叫从主线程移出。 Android 4在主线程上禁止网络调用以防止ANR问题。 – 2012-02-13 22:47:20

+2

这将建立一个完整的3路握手TCP连接。所以这个时间就像是一个ping('ICMP-echo - > ICMP-reply') – 2015-03-04 19:51:29