简体   繁体   English

使用ADB截屏并在Java中检索它而无需编写文件

[英]Take screenshot with ADB and retrieve it in java WITHOUT writing a file

I know that one can take a screenshot from the Android device via ADB with 我知道可以通过ADB通过Android设备从屏幕截图

$ adb shell screencap -p /mnt/sdcard/sc.png
$ adb pull /mnt/sdcard/sc.png

However this writes a file on your phone and on your PC, which I want to avoid. 但是,这会在您的手机和PC上写入一个文件,我想避免这样做。

So I found the following SO question and the answer suggested that the image gets printed to the Std output when you do not specify a file. 因此,我发现了以下SO问题,答案表明当您不指定文件时,图像将被打印到Std输出。 I tested this from console and it really printed binary data to the console. 我从控制台进行了测试,它确实将二进制数据打印到了控制台。

Android: It there a way to read screenshot from memory without saving to internal/external storage? Android:有没有办法从内存读取屏幕截图而不保存到内部/外部存储?

Now I want to utilize this technique and start a process from java, execute the 现在,我想利用这种技术并从Java启动一个进程,执行

adb shell screencap

command, read the output and create a BufferedImage from the output. 命令,读取输出并从输出创建BufferedImage。

I tried something like this 我尝试过这样的事情

ProcessBuilder pb = new ProcessBuilder("cmd"); 
Process start = pb.start();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
bw.write("adb shell screencap");
bw.newLine();
bw.flush();
// wait some time for the process to print the image to the console
start.waitFor(10, TimeUnit.SECONDS);
StringBuilder sb = new StringBuilder(9000000);
Scanner s = new Scanner(start.getInputStream());
while (s.hasNext()) {
      sb.append(s.next());
}
String result = sb.toString();

Unluckily there are quite a few issues with my Code. 不幸的是我的代码有很多问题。

  1. the program does not terminate after getting the screenshot - so start.waitFor does not quite work as I wanted it to work 该程序在获取屏幕快照后不会终止-因此start.waitFor不能正常工作,因为我希望它能工作

  2. currently my code reads characters, where i actually want to read bytes 目前,我的代码读取字符,而我实际上想读取字节

  3. reading with scanner seems kind of slow when reading millions of characters/bytes 读取数百万个字符/字节时,使用扫描仪读取似乎有点慢

Maybe someone can point me in a direction such that I can get it to work. 也许有人可以指出我的方向,使我可以正常工作。 Thanks! 谢谢!

Why complicating things. 为什么使事情复杂化。 If you are invoking adb and want its output just run 如果您正在调用adb并希望其运行

adb exec-out screencap -p > myimg.png

exec-out is used instead of shell to get raw data (ie the image). exec-out代替shell来获取原始数据(即图像)。

After searching some more time I came across ddmlib which already has the functionality to take screenshots and perform various other tasks via ADB built in. 经过一段时间的搜索后,我遇到了ddmlib ,它已经具有拍摄屏幕截图并通过内置的ADB执行各种其他任务的功能。
The library works great and definitely made it easier for me to execute commands via ADB. 该库运行良好,无疑使我可以更轻松地通过ADB执行命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM