2

我正在编写一个文件资源管理器,它能够以 root 访问权限修改系统文件,但我遇到了一些问题。

我现在正在做的是授予我的应用程序 root 访问权限,但是执行“su”不起作用。如果我在 adb shell 中设置文件夹的权限,该应用程序可以正常工作,但我认为 root 浏览不依赖 chmods。

谁能告诉我有没有一种正确的方法可以让我的应用程序像使用 root 权限一样工作?

4

2 回答 2

2

以 root 身份运行 android 应用程序进程(其 dalvik VM 和本机库)非常难以实现,并且出于多种原因不建议使用,不仅包括安全性,还包括由于必须加载系统库的私有副本而不是使用共享而导致的内存浪费当您从 zygote 继承非特权进程时,只读副本可用,就像在正常应用程序启动中一样。

一些有根手机的非官方“su”hack 所做的是让您启动一个以 root 身份运行的辅助进程,而您的应用程序进程仍然没有特权。它不会改变调用它的应用程序的用户 ID——事实上,在类 unix 操作系统上确实没有设计任何机制来做到这一点。

一旦你有一个特权助手进程,你就需要通过一些进程间通信方式与它通信,例如它的标准输入/标准输出或 unix 域套接字,让它代表你执行文件操作。手机上的外壳甚至可以用作辅助应用程序——文件管理器需要做的大部分事情都可以通过“cat”命令来实现。正式地,这都不是一个稳定的 API,但是一个应用程序可访问的“su”hack 无论如何都不在官方 android 中,所以整个项目一开始就处于“不受支持”的领域。

于 2011-07-04T15:20:22.160 回答
1

根访问创建一个新进程,因此,您的应用程序没有根权限。
使用root权限可以做的独特的事情是执行命令,所以,你必须知道android的命令,许多命令是基于Linux的,比如cpls等等。

使用此代码执行命令并获取输出:

/**
 * Execute command and get entire output
 * @return Command output
 */
private String executeCommand(String cmd) throws IOException, InterruptedException {
    Process process = Runtime.getRuntime().exec("su");
    InputStream in = process.getInputStream();
    OutputStream out = process.getOutputStream();
    out.write(cmd.getBytes());
    out.flush();
    out.close();
    byte[] buffer = new byte[1024];
    int length = buffer.read(buffer);
    String result = new String(buffer, 0, length);
    process.waitFor();
    return result;
}

/**
 * Execute command and an array separates each line
 * @return Command output separated by lines in a String array
 */
private String[] executeCmdByLines(String cmd) throws IOException, InterruptedException {
    Process process = Runtime.getRuntime().exec("su");
    InputStream in = process.getInputStream();
    OutputStream out = process.getOutputStream();
    out.write(cmd.getBytes());
    out.flush();
    out.close();
    byte[] buffer = new byte[1024];
    int length = buffer.read(buffer);
    String output = new String(buffer, 0, length);
    String[] result = output.split("\n");
    process.waitFor();
    return result;
}

文件资源管理器的用法:

获取文件列表:

for (String value : executeCmdByLines("ls /data/data")) {
    //Do your stuff here
}

读取文本文件:

String content = executeCommand("cat /data/someFile.txt");
//Do your stuff here with "content" string

复制文件(cp命令在某些设备上不起作用):

executeCommand("cp /source/of/file /destination/file");

删除文件(rm命令在某些设备上不起作用):

executeCommand("rm /path/to/file");
于 2015-09-11T01:01:37.387 回答