开发者

How to ping a URL in an Android Service?

开发者 https://www.devze.com 2022-12-29 05:40 出处:网络
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.I think if you just want

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.


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); // 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();
}

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.

hopes that helps

code snippet found in here

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号