How can ping website from android to get average time of server response.

I am making an android application which can get ping response time from android application. I have already done it with windows environment but when i take it onto android device, device can't send any response. How can i solve this problem.?

Thanks in advance. here is my code

                 String ip="www.google.com"; String pingResult="  ";
                String pingCmd="ping"+ip;

                Runtime r=Runtime.getRuntime();
                Process p=r.exec(pingCmd);
                BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
                String inputLine;
                Toast.makeText(getApplicationContext(), "Going loop", 1).show();
                while((inputLine=in.readLine())!=null)
                {
                    pingResult=inputLine;
                }
                Toast.makeText(getApplicationContext(),pingResult, 1).show();
                in.close();

Upvotes: 2

Views: 3485

Answers (1)

Luis
Luis

Reputation: 12058

Your will work fine if you change the line:

Process p=r.exec(pingCmd); 

to:

Process p=r.exec(new String[] {"ping", "-c 4", "www.google.pt"}); 

The reason is:

-Android exec command expects a String[] instead of String.

-The -c parameter is required to limit the number of pings to 4 (to replicate the windows behaviour). Otherwise it will ping forever.

Finally, this only works on a real device. To have it working in the emulator, you would need to configure adb to redirect ping replays to the emulator.

Good luck.

Upvotes: 1

Related Questions