Android以编程方式执行su命令不起作用 [英] Android- performing su commands programatically does not work

查看:277
本文介绍了Android以编程方式执行su命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的应用以编程方式执行一些 su 命令(手机已植根).

I need my app to perform some su commands programatically (phone is rooted).

使用adb完成后,这些命令将起作用.

When done using adb, the commands work.

例如: su -c"mkdir/sdcard/testdir" 在/sdcard中创建一个名为"testdir"的目录.

For instance: su -c "mkdir /sdcard/testdir" creates a directory called "testdir" in /sdcard.

当我打电话时:

    p = Runtime.getRuntime().exec("su -c \"mkdir /sdcard/testdir\"");
    p.waitFor();

它只是继续前进,没有任何变化.

It just moves on and no change happens.

我尝试读取输入内容:

DataInputStream dis = new DataInputStream(p.getInputStream());
    while((temp = dis.readLine())!=null)
        Log.d(ctx.TAG,"shell:"+temp);

但是它什么也没报告(循环执行0次迭代).

But it reports nothing (loop does 0 iterations).

以前有没有人遇到过这个问题?怎么解决呢?如今,非su命令可以通过此方法以编程方式运行.

Has anyone ever faced this issue before? How can it be solved? Needless to day, non-su commands do work programatically with this method.

注意:我以 mkdir 为例(我知道它不一定需要su).我需要在 su

Note: I gave mkdir as an example (I know it doesn't necessarily require su). I need a lot of varied commands to be performed under su

谢谢!

当我以编程方式调用 su -c"id" 时,输出为uid = 0.

when I call su -c "id" programatically, there's output that uid=0.

推荐答案

几天之内我都会陷入困境,而当我鼓起勇气在StackOverflow上提出问题时,几分钟之内就解决了.

I can get stuck on a problem for days, and the moment I gather up the courage to ask about it on StackOverflow, it is solved within minutes.

解决方法是:

    p=Runtime.getRuntime().exec("su");
    DataOutputStream dos = new DataOutputStream(p.getOutputStream());
    dos.writeBytes("mkdir /sdcard/testdir\n");
    dos.writeBytes("exit\n");
    dos.flush();
    dos.close();
    p.waitFor();

在您向 DataOutputStream 写入的每个命令的结尾不要忘记 \ n ,因为没有它将无法工作.

Don't forget \n at the end of each command you write to the DataOutputStream, as it will not work without it.

这篇关于Android以编程方式执行su命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆