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

Emi*_*enT 13 shell android screenshot adb

我试图以编程方式执行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");
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

日志中的问题:

07-31 15:26:31.832 18716-18716/com.example E/Output:无法绑定'tcp:5038'*守护程序未运行.现在从5038号港口开始

我无法截取屏幕截图,但如果我在命令提示符下运行相同的命令,那么这个工作正常.

但是如果我执行

new ExecuteCommand(MainActivity.this).execute("ls");
Run Code Online (Sandbox Code Playgroud)

这很好用.指挥中的问题在哪里?

小智 5

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

这将是干净的:

new ExecuteCommand(MainActivity.this).execute("screencap -p " + f);
Run Code Online (Sandbox Code Playgroud)


Abh*_*hek 5

在本网站和android-developers上已经有过几次类似的讨论,但是 TL:DR 是您无法真正从设备运行所有 shell 命令。其中大多数需要仅授予系统应用程序的权限。pm例如,使用shell 命令需要各种包权限,其中大多数仅是系统权限。您可以在此处检查权限列表。

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