2

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

1 回答 1

0

一种选择是创建一个新线程来 ping,并将其保持打开一段时间(称为超时)。如果您没有得到想要的响应,在想要的时间内,您可以关闭线程并重试;或者,终止进程。这将使您能够检查特定的响应代码以及超时。

于 2013-07-08T20:19:31.920 回答