星期三, 1月 18, 2012

ping in Android(續)

後來發現裏面有包ping這指令,而且有設置setgid權限,那麼應該是可以執行。只是試了之後,卻不行,然後我就以為不行。之後不死心,把stderr接出來看,才知道我下錯指令,於是修正以後,就可以了。

final class Helper {
  private final String TAG="Helper";
  private void pingInExec(String host) {
    Runtime runtime = Runtime.getRuntime();
    String command = String.format("/system/bin/ping -c 2 %s", host);
    Process proc;
    try {
      proc = runtime.exec( command );
      BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      BufferedReader err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
      
      String inputLine;
      while ((inputLine = in.readLine()) != null) {
        Log.d(TAG, inputLine );
      }
      in.close();
      while ((inputLine = err.readLine()) != null) {
        Log.e(TAG, inputLine );
      }
      err.close();
      proc.waitFor();
      int exit = proc.exitValue();
      Log.d(TAG, String.format("exitcode=%d", exit) );
      if (exit == 0) { // normal exit
        Log.d(TAG, "RESPONSE_OK");
      } else { // abnormal exit, so decide that the server is not reachable
        Log.d(TAG, "RESPONSE_TIMEOUT" );
      }
    } catch (IOException e) {
      Log.e( TAG, e.getMessage() );
    } catch (InterruptedException e) {
      Log.e( TAG, e.getMessage() );
    }
  }
}

沒有留言:

您或許對這些文章有興趣

Related Posts Plugin for WordPress, Blogger...