如何在Android服务中ping URL? [英] How to ping a URL in an Android Service?
本文介绍了如何在Android服务中ping URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Android服务执行ping回调?我需要在单击按钮时打开一个网页,但是在后台,请ping其他用于统计信息收集的URL.
How can I use Android Service to do a ping callback? I need to open a webpage on a button click, but in the background, go ping another URL for stats collection.
推荐答案
我认为,如果您只想ping通URL,则可以使用以下代码:
I think if you just want to ping an url, you can use this code :
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()并计算差值.
And, if you want to have the equivalent of a ping, you can put a System.currentTimeMillis() before and after the call, and calculate the difference.
希望有帮助
代码段
这篇关于如何在Android服务中ping URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文