android - 读取 su 进程内的命令输出

标签 android root su

首先我介绍一下我的情况。 我需要在我的 android 应用程序中执行“su”命令,它运行良好。然后我需要执行“ls”命令并读取输出。我通过从“su”进程获取输出流并将我的命令写入其中来做到这一点。

问题来了。如何读取“ls”过程的输出?我所拥有的只是“su”过程对象。从它获取输入流什么也没有,因为“su”不写任何东西。但是“ls”可以,但我不知道如何访问它的输出消息。

我搜索了很多网站,但没有找到任何解决方案。也许有人会帮助我:)

问候

最佳答案

好的,我找到了解决方案。它应该看起来像这样:

Process p = Runtime.getRuntime().exec(new String[]{"su", "-c", "system/bin/sh"});
DataOutputStream stdin = new DataOutputStream(p.getOutputStream());
//from here all commands are executed with su permissions
stdin.writeBytes("ls /data\n"); // \n executes the command
InputStream stdout = p.getInputStream();
byte[] buffer = new byte[BUFF_LEN];
int read;
String out = new String();
//read method will wait forever if there is nothing in the stream
//so we need to read it in another way than while((read=stdout.read(buffer))>0)
while(true){
    read = stdout.read(buffer);
    out += new String(buffer, 0, read);
    if(read<BUFF_LEN){
        //we have read everything
        break;
    }
}
//do something with the output

希望对大家有帮助

关于android - 读取 su 进程内的命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6896618/

相关文章:

android - 授予管理员访问 Android 应用程序的权限

Android 我的应用程序在 2.3 上运行良好,但即使在 4.0 上也无法启动

c# - Xamarin.Forms 动态按钮样式

android - DialogPreference 导致错误 onDisplayPreferenceDialog()

android - 自动完成 TextView getSelectedItemPosition

android - FileExplorer eclipse 作为 root

java - 如何获取 Android 应用程序的提升权限

asp.net-mvc-4 - IIS 重写不适用于应用程序的根目录

android - 从 Android 应用程序中的 busybox 命令获取输出

bash - su输入命令中如何定义环境变量