title: Android - Interactive shell (Runtime.getRuntime().exec())
body: <p>How to run an interactive shell on android? (rooted device)</p>
  
  <p>I need the nexts steps:</p>
  
  <p>1 - Execute shell process (onCreate)</p>
  
  <pre><code>Process p = Runtime.getRuntime().exec(String[]{"su","-c","sh"});
  </code></pre>
  
  <p>2 - Get the output (onCreate)<br /></p>
  
  <pre><code>BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream));
  //dos is a field (a class attribute)
  dos = new DataOutputStream(p.getOutputStream());
  new Thread(new Runnable() {
  
      @Override
      public void run() {
           String l;
           //wait the console output and write it
           while((l = br.readLine()) != null) {
                Log.v("info", l);
           }
      }
  }).start();
  </code></pre>
  
  <p>3 - Execute a command (Button -> onClick())</p>
  
  <pre><code>cmd("wpa_cli");
  </code></pre>
  
  <p>The cmd method is:</p>
  
  <pre><code>public void cmd(String cmd) {
     dos.writeBytes(cmd + "\n");
     dos.flush();
  }
  </code></pre>
  
  <p>The Log never shows the console output.</p>
  
  <p>Next step:</p>
  
  <p>4 - Get the output of a subcommand of wpa_cli (another Button -> onClick())</p>
  
  <pre><code>cmd("help");
  </code></pre>
  
  <p>Should show the wpa_cli help but it doesn't work.<br />
  If i press the button many times appears incomplete output (help)</p>
  
  <p>What is the correct way to initialize a process when the Activity is creating and keep it active to interact?</p>
  
  <p>Thanks.</p>
  
  <p>PostData<br />
  I replaced the line <code>Log.v("info", l);</code> <br />
  with <br /></p>
  
  <pre><code>fos.write(l);
  Message msg = handlerTest.obtainMessage();
  msg.obj = l;
  handlerTest.sendMessage(msg);
  </code></pre>
  
  <p>fos -> FileOutputStream object</p>
  
  <pre><code>Handler handlerTest = new Handler() {
      @Override
      handleMessage(Message msg) {
         if (msg != null) {
           //alert... (String)msg.obj;
         }
      }
  }; 
  </code></pre>
  
  <p>And only displays the alert from the direct commands, as <code>help</code> for example. The command <code>status</code> only work when the stream is closed. (after execute <code>cmd("quit");</code> and <code>cmd("exit");</code>)</p>
  
  <p>I don't understand. stdout is more that one? I can interact with the output without close the stream?</p>
  
  <p>With <code>adb shell</code> i read the output file (created after closing the stream) and it's complete.</p>
  
  <p>PostData2:</p>
  
  <p>The problem is the buffer. Between the binary file (executed) output and java process i can disable the buffer without using Native I/O?
  The Android Terminal Emulator works fine, it's using NIO?</p>