简体   繁体   中英

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 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.

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. 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?

Now I want to utilize this technique and start a process from java, execute the

adb shell screencap

command, read the output and create a BufferedImage from the output.

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

  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 exec-out screencap -p > myimg.png

exec-out is used instead of shell to get raw data (ie the image).

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.
The library works great and definitely made it easier for me to execute commands via ADB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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