从Java程序执行ADB命令 [英] Execute ADB command from Java program

查看:1962
本文介绍了从Java程序执行ADB命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的程序使用ADB(Android Debug Bridge)将文件发送到我的手机:

The program I'm working on uses ADB (Android Debug Bridge) to send files to my phone:

for (String s : files)
    String cmd = "adb -s 0123456789ABCDEF push " + s + " /mnt/sdcard/" + s;
    try {
        InputStream is = Runtime.getRuntime().exec(cmd).getInputStream();
        while (is.read() != -1) {}
    } catch (IOException e) {
        e.printStackTrace();
    }

我希望程序等到ADB完成传输,但ADB运行为一个守护进程,因此永远不会完成。但该程序仍在继续,不知何故文件不会发送到我的手机(日志中没有例外)。当我从控制台运行命令时,它没有问题。

I want the program to wait until ADB finished the transmission, but ADB runs as a daemon and therefore never finishes. But the program continues immideately and somehow the files aren't sent to my phone (no exceptions in log). When I run the command from console, it's working without problems.

我做错了什么?如何通过ADB正确发送文件?

What am I doing wrong? How do I send files via ADB correctly?

注意: is.read()== -1 赢了不起作用,因为ADB守护程序将所有输出写入系统标准输出。我已经尝试将其转发到文本文件中。它保持空白,输出仍然写入终端

NOTE: the is.read() == -1 won't work, because the ADB daemon writes all output to the system standard output. I've tried forwarding it into a textfile. It stayed empty and the output was still written to the terminal instead

编辑:读取ADB流程的ErrorStream返回每个adb帮助 adb push -command。再次:完全命令(从Eclipse控制台复制)在终端中工作

EDIT: Reading the ErrorStream of the ADB process returned the adb help for each adb push-command. Again: The exact commands (copied from Eclipse console) work in a terminal

编辑2 :使用ProcessBuilder而不是 RUntime.getRuntime.exec()导致以下错误:

EDIT 2: Using a ProcessBuilder instead of RUntime.getRuntime.exec() resulted in the following error:

java.io.IOException: Cannot run program "adb -s 0123456789ABCDEF push "inputfile "outputfile""": error=2, File or directory not found

在ProcessBuilder的 start() -method
使用ADB的绝对路径时会发生同样的情况(的/ usr /斌/ ADB )。 inputfile和outputfile字符串也是绝对路径,如 / home / sebastian / testfile 并且肯定存在。当从终端运行命令时(字符串cmd打印,复制和粘贴),evreything仍然正常。

at the ProcessBuilder's start()-method The same happens when using an absolute path for ADB (/usr/bin/adb). The inputfile and outputfile Strings are also absolute paths, like /home/sebastian/testfile and definitely exist. When running the commands from terminal (string "cmd" printed, copy&paste), evreything still works fine.

推荐答案

我终于让它工作:

ProcessBuilder pb = new ProcessBuilder("adb", "-s", "0123456789ABCDEF", "push", inputfile, outputfile);
Process pc = pb.start();
pc.waitFor();
System.out.println("Done");

我不知道有什么问题 ProcessBuilder 在字符串中有空格,但最后,它正在工作......

I don't know what problems ProcessBuilder has with spaces in a string, but finally, it's working...

这篇关于从Java程序执行ADB命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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