13

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.

halfer
  • 19,471
  • 17
  • 87
  • 173
Chris
  • 3,727
  • 12
  • 40
  • 49
  • Kotlin implementation supporting API 25+ can be found here: https://stackoverflow.com/questions/53402128/ping-website-url-before-loading-it-in-webview-in-android-kotlin/53402129 – quietbits Nov 20 '18 at 23:33

1 Answers1

25

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

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

Community
  • 1
  • 1
Sephy
  • 49,272
  • 30
  • 120
  • 129
  • This has been working fine for me except for Android 4 devices where it always fails. Any ideas? – dee Feb 10 '12 at 16:29
  • 10
    You need to move the call off your main thread. Android 4 enforces no network calls on the main thread to prevent ANR issues. – Nick Campion Feb 13 '12 at 22:47
  • 4
    This will establish a TCP connection with a full 3-way handshake. So the time is nothing like a ping (`ICMP-echo -> ICMP-reply`) – Fredrik Erlandsson Mar 04 '15 at 19:51
  • @NickCampion: for me this code is not working on 4.2.2 device which includes samsung s3 and other , any solution – Punit Sharma Feb 10 '16 at 10:32