gpt4 book ai didi

android - 如何在运行时使用 "su"发送命令并从 DataInputStream 取回所有行

转载 作者:搜寻专家 更新时间:2023-11-01 08:06:04 25 4
gpt4 key购买 nike

我正在开发一个程序,该程序需要能够确定 Xlocation 上的 android 设备上有什么。我正在使用“su ls Xlocation”

我想取回文件数组列表,但只设法取回第一个项目。我是否缺少获取下一行的命令?或者还有什么我需要做的。

下面是我发送的指令

String[] commands = new String[]{"ls /system/app/"};
return doCommand(commands);

下面是我目前的 doCommand 方法

    private boolean doCommand(String[] commands)
{
ArrayList<String> output = new ArrayList<String>();

boolean ran = false;
try
{
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
DataInputStream ins = new DataInputStream(process.getInputStream());

// This part works I sends the command right!
for (String single : commands)
{
os.writeBytes(single + "\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
process.waitFor();
ran = true;
}

int av = -1;
while (av != 0)
{

//////////////////////////// WORKING ON THIS TO GET ALL INFO /////////////////
av = ins.available();
if (av != 0)
{
byte[] b = new byte[av];
ins.read(b);
output.add(new String(b));
System.out.println(new String(b) + "Recieved form modem");
}
}
}
catch(Exception ex){}
return ran;
}

如目前所见,它只返回 true 或 false。但是在调试中运行我只得到输出中的第一项。 (output = "[first.apk")

编辑较新的版本;

    public ArrayList<String> doCommand(String[] commands)
{

ArrayList<String> output = new ArrayList<String>();

try
{

Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
DataInputStream ins = new DataInputStream(process.getInputStream());
for (String single : commands)
{
os.writeBytes(single + "\n");

//os.flush();
output.add("true");
}
os.writeBytes("exit\n");


byte[] bc = new byte[10000];
String st = "";
while(ins.read(bc) != -1)
{
st += new String(bc);
os.flush();

}
output.add(st);


os.flush();
os.close();
ins.close();
process.waitFor();
}
catch(Exception ex)
{}

return output;
}

现在得到了相当数量的输出,但仍然不是所有的目录都有大项目在字节 [10000] 的大小限制内,我已经检查过。

如果有人想对此进行改进并获得有效的确切答案,那么我仍然会查看这篇文章。

谢谢

最佳答案

您可以尝试从我的开源用户管理 (GitHub) 应用程序中调整此方法来执行您想要的操作。这将读取终端命令后输出的每一行:

public static String[] getUserList()
{
Process p;
try {
p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()));

os.writeBytes("pm list-users"+"\n");
os.writeBytes("exit\n");
ArrayList<String> users = new ArrayList<String>();
String test;
bf.readLine();
while((test = bf.readLine()) != null)
{
users.add(test);
}

String[] userList = (String[]) users.toArray(new String[users.size()]);



os.flush();
return userList;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

关于android - 如何在运行时使用 "su"发送命令并从 DataInputStream 取回所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14267057/

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