Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("tcpdump\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.

like image 863
Jimix Avatar asked Dec 06 '25 22:12

Jimix


2 Answers

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);
like image 143
Wizzard256 Avatar answered Dec 08 '25 14:12

Wizzard256


Combine TextView.append method with Handler

Here is good example:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html

like image 38
pawelzieba Avatar answered Dec 08 '25 13:12

pawelzieba