gpt4 book ai didi

android - 如何将进程的标准输出绑定(bind)到 TextView

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:42 24 4
gpt4 key购买 nike

我正在开发我的第一个 Android 应用程序。我需要以 root 用户身份在 shell 中执行命令,所以我在我的应用程序中引入了这段代码:

process = Runtime.getRuntime().exec("su");

然后我获取到进程的输出流,并使用它来执行命令:

os = new DataOutputStream(process.getOutputStream());

os.writeBytes("tcpdump\n");

然后我获得一个输入流,我想用它来显示过程的结果:

is = new DataInputStream(process.getInputStream());

我想将获得的 DataInputStream 绑定(bind)到布局中的 TextView,以便它显示的文本在处理继续显示结果时实时更新。

我一直在搜索适用于 android 的 java.io API,但找不到一种简单的方法来执行此操作。我一直在考虑运行一个带有循环的线程,该循环不断检查输入流中是否有新数据,然后将其复制到 TextView 但这似乎是一个蹩脚的解决方案。

如果有人知道如何做到这一点,我将非常感谢。

最佳答案

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

关于android - 如何将进程的标准输出绑定(bind)到 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5065408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com