如何使用 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); // Timeout 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 https://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)