很多时候对Android系统底层进行操作(如查看/data/data/下的数据)是没有权限的。当然如果能在Java层直接执行的操作,直接用类似如下代码执行即可:
Process process;
String cmd = "....";
try {
process = Runtime.getRuntime().exec("su");
BufferedReader reader = new BufferedReader(new InputStreamReader(
process.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
process.getOutputStream()));
BufferedReader error = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
writer.write(cmd + "\n");
writer.write("exit\n");
writer.flush();
String line;
while ((line = reader.readLine()) != null) {
// 处理结果
}
while ((line = error.readLine()) != null) {
Log.e("error", line);
}
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}这里我们用命令行来演示一下:
android:/ $ du -ah /data/data/com.example.helloworld/ du: can't open '/data/data/com.example.helloworld/': Permission denied这里我们可以看到没有权限。但是当我们通过“su -c cmd”来执行上述命令的时候就会获得root权限来执行:
@android:/ $ su -c "du -ah /data/data/com.example.helloworld/" 8.0K /data/data/com.example.helloworld/lib/libhelloworld.so 12.0K /data/data/com.example.helloworld/lib 4.0K /data/data/com.example.helloworld/cache/com.android.renderscript.cache 8.0K /data/data/com.example.helloworld/cache 1.0M /data/data/com.example.helloworld/files/busybox 4.0K /data/data/com.example.helloworld/files/test 1.0M /data/data/com.example.helloworld/files 1.1M /data/data/com.example.helloworld/
(从stackoverflow的到的思路,未实际操作过)
(use the NDK toolchain to cross-compile native program as a binary)
然后通过Java层通过su来调用。
(我自己项目用到busybox就是通过这个方法来执行的)
这个应该和第2种方法异曲同工吧。
原文:http://blog.csdn.net/jiezhi2013/article/details/42424497