【发布时间】:2011-02-16 17:18:00
【问题描述】:
如何使用 Android 服务进行 ping 回调?我需要在单击按钮时打开一个网页,但在后台,去 ping 另一个 URL 以收集统计信息。
【问题讨论】:
-
支持 API 25+ 的 Kotlin 实现可以在这里找到:stackoverflow.com/questions/53402128/…
如何使用 Android 服务进行 ping 回调?我需要在单击按钮时打开一个网页,但在后台,去 ping 另一个 URL 以收集统计信息。
【问题讨论】:
我想如果你只是想 ping 一个 url,你可以使用这个代码:
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(),然后计算差值。
希望有帮助
代码 sn-p 在here 中找到
【讨论】:
ICMP-echo -> ICMP-reply)