How to bind the standard output of a process to a TextView
I'm developping my first Android App. I need to execute a command in a shell as the root user so I've introduced this code in my App:
process = Runtime.getRuntime().exec("su");
Then I obtain an output stream to the process and I use it to execute the command:
os = new DataOutputStream(process.getOutputStream());
os.writeBytes("t开发者_开发技巧cpdump\n");
Then I obtain an input stream which I want to use for displaying the results of the process:
is = new DataInputStream(process.getInputStream());
I would like to bind the obtained DataInputStream to a TextView in the layout so the text that it displays gets updated in real time as the process goes on showing results.
I've been searching trought the java.io API for android and I can't find an easy way to do this. I've been thinking in running a thread with a loop which continously checks if there is new data in the input stream and then copy it to the TextView but this seems a crappy solution.
I would thank you if anyone knows a way to do this.
Channel channel = session.openChannel("shell");
OutputStream os = new OutputStream() {
@Override
public void write(int oneByte) throws IOException {
TextView textView1 = (TextView) findViewById(R.id.textView1);
char ch = new Character((char) oneByte);
textView1.setText(textView1.getText() + String.valueOf(ch));
System.out.write(oneByte);
}
};
// channel.setOutputStream(System.out);
channel.setOutputStream(os, true);
Combine TextView.append method with Handler
Here is good example:
http://android-developers.blogspot.com/2007/11/stitch-in-time.html
I've been able to set a Handler and start a runnable which will read from the input stream every 200ms.
Despite this, it seems that the input stream isn't receiving any characters form the process standard output and everytime I call a read() method it gets blocked waiting for characters that never come. I've been trying following this two websites instructions without sucess:
http://gimite.net/en/index.php?Run%20native%20executable%20in%20Android%20App
http://code.google.com/p/market-enabler/wiki/ShellCommands
Thanks.
After one day of research and tests, I found that the only solution for this problem is using AsyncTask. You can adapt this code, which is working fine: https://stackoverflow.com/a/9063257 It also works replacing ProcessBuilder() with Runtime.getRuntime() if you like it.
精彩评论