很多时候对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();
}
但是有时候我们需要在Jni层进行类似的操作,那么我们如何获取root权限呢?这边提供四种思路供大家参考(前提是手机已root,有的思路未经实践,如果不可行或有更好的方法,还望斧正):
1.通过“su -c”来执行:
这里我们用命令行来演示一下:
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/
在jni的native 层可以同过此方法来执行。
2.sign Android app with system signature
(从stackoverflow的到的思路,未实际操作过)
3.将native层编译成可执行文件
(use the NDK toolchain to cross-compile native program as a binary)
然后通过Java层通过su来调用。
(我自己项目用到busybox就是通过这个方法来执行的)
4.copy app to /system/app/
这个应该和第2种方法异曲同工吧。
原文:http://blog.csdn.net/jiezhi2013/article/details/42424497