I have been trying to attempt to insert a ping command thread into my Android application, and when the server is reachable the code works great. When the server is unreachable, the process hangs and I have no idea why.
This code works in the emulator, whether the host is resolvable or not, however on an actual device, the process.waitFor never returns, and no output is published from the input or output streams.
Any ideas?
protected double executePing(String ipAddress) {
List<String> commands = new ArrayList<String>();
commands.add("/system/bin/ping");
commands.add("-c");
commands.add("5");
commands.add("-w");
commands.add("5");
commands.add("128.128.128.128");
try {
this.doCommand(commands);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return laten;
}
private void doCommand(List<String> command) throws IOException{
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(
process.getErrorStream(), "ERROR");
// any output?
OutputStreamGobbler outputGobbler = new OutputStreamGobbler(
process.getInputStream(), "OUTPUT");
// kick them off
errorGobbler.start();
outputGobbler.start();
// read the output from the command
try {
exitVal = process.waitFor();
//Sleep for 10 secs to try to clear the buffer
Thread.sleep(6000);
//pingVal = echo.toString();
if(exitVal == 0 && !pingVal.isEmpty()){
//System.out.println("PING STATS: "+pingVal);
try{
pingVal = pingVal.substring(pingVal.lastIndexOf("rtt min/avg/max/mdev"));
pingVal = pingVal.substring(23);
pingVal = pingVal.substring(pingVal.indexOf("/")+1);
laten = Double.parseDouble(pingVal.substring(0,pingVal.indexOf("/")));
}catch (IndexOutOfBoundsException ex){
System.out.println("PING VAL: "+ pingVal);
ex.printStackTrace();
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ExitValue: " + exitVal);
}