【问题标题】:How to ping a URL in an Android Service?如何在 Android 服务中 ping 一个 URL?
【发布时间】:2011-02-16 17:18:00
【问题描述】:

如何使用 Android 服务进行 ping 回调?我需要在单击按钮时打开一个网页,但在后台,去 ping 另一个 URL 以收集统计信息。

【问题讨论】:

标签: android url service ping


【解决方案1】:

我想如果你只是想 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 中找到

【讨论】:

  • 这对我来说一直很好,除了总是失败的 Android 4 设备。有什么想法吗?
  • 您需要将调用移出主线程。 Android 4 不强制主线程上的网络调用来防止 ANR 问题。
  • 这将建立一个完整的 3 次握手的 TCP 连接。所以时间一点也不像 ping (ICMP-echo -> ICMP-reply)
  • @NickCampion:对我来说,此代码不适用于 4.2.2 设备,其中包括 samsung s3 和其他任何解决方案
猜你喜欢
  • 2011-08-26
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多