以编程方式执行adb命令时出现错误

13

我正在尝试以编程方式执行adb命令。

这是我的代码:

File f = new File(Environment.getExternalStorageDirectory(), "screen" + System.currentTimeMillis() + ".png");

new ExecuteCommand(MainActivity.this).execute("adb shell screencap -p "
        + Environment.getExternalStorageDirectory().getPath() +
        "/" + "screen" + System.currentTimeMillis() + ".png");

ExecuteCommand类:

public class ExecuteCommand extends AsyncTask<String, String, String> {

    Context mContext=null;
    public ExecuteCommand(Context _ctx)
    {
        mContext =_ctx;
    }

    ProgressDialog progressdailog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressdailog = ProgressDialog.show(mContext,
                "Executing", "Please Wait");
    }
    @Override
    protected String doInBackground(String... params) {
        Process p;
        StringBuffer output = new StringBuffer();
        try {
            p = Runtime.getRuntime().exec(params[0]);
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
                p.waitFor();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String response = output.toString();
        return response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressdailog.dismiss();
        Log.e("Output", result);
    }
}

日志中的问题:

07-31 15:26:31.832 18716-18716/com.example E/Output﹕无法绑定'tcp:5038'*守护进程未运行。现在在端口5038上启动。

我无法截图,但如果我在命令提示符上运行相同的命令,则可以正常工作。

但是,如果我执行

new ExecuteCommand(MainActivity.this).execute("ls");

这个可以正常工作。命令有什么问题吗?


为什么exec()会启动ADB守护进程? - Onik
3个回答

5
在这个网站和android-developers上都有几次类似的讨论,但是总的来说,你不能真正从设备上运行所有的shell命令。大多数命令需要授予系统应用程序的权限。例如,使用pm shell命令需要各种包权限,其中大部分是仅限系统的。您可以在此处检查权限列表here

你要么必须对设备进行root,要么寻找替代方法来实现你想要的功能。


5

adb shell 是在您执行命令以尝试访问设备时在 PC 上使用的。但是当您在设备本身上执行命令时,不需要 adb shell

这将是干净的:

new ExecuteCommand(MainActivity.this).execute("screencap -p " + f);

这个不起作用。现在的输出是 [ 07-31 15:38:11.494 1039:0x502 D/KeyguardViewMediator ] setHidden false。 - Amarjit
setHidden false 可能不是问题所在。当您删除 adb shell 命令时,这可能是唯一的输出? - Thiago Moura
从KeyguardViewMediator中获取的日志不会影响此问题,需要在其他地方查找。屏幕录制可以在锁屏状态下进行录制,因此无论是否可见都没有影响。 - JoxTraex
是的,但截图没有保存或可能没有被拍摄。 - Amarjit

2

谢谢!!! 但是我需要使用命令行中的一些东西,因为我还必须使用其他ADB命令!! - Amarjit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接