如何在 Android 服务中 ping 一个 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2786720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:23:12  来源:igfitidea点击:

How to ping a URL in an Android Service?

androidurlserviceping

提问by Chris

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.

如何使用 Android Service 进行 ping 回调?我需要单击按钮打开一个网页,但在后台,去 ping 另一个用于统计数据收集的 URL。

回答by Sephy

I think if you just want to ping an url, you can use this code :

我想如果你只是想 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();
}

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.

并且,如果你想要一个 ping 的等价物,你可以在调用前后放置一个 System.currentTimeMillis(),并计算差异。

hopes that helps

希望有帮助

code snippet found in here

这里找到的代码片段