如何在 Android 服务中 ping 一个 URL? [英] How to ping a URL in an Android Service?

查看:29
本文介绍了如何在 Android 服务中 ping 一个 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Android Service 进行 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆