Execute ADB Command

There are two ways to execute ADB command, in command prompt and Java.

Execute ADB Command in Command Prompt

Before I programming in Java, I tried my code in Command Prompt, like this

adb shell screencap -p /sdcard/screenshot.png
adb pull /sdcard/screenshot.png D:\\screenshot.png
adb shell rm /sdcard/screenshot.png

It looks good, and I got the screenshot to my computer too. So I use

Runtime.getRuntime().exec(String command);

to execute the last three commands, but nothing happened.

Execute ADB Command in Java

It takes me a lot of time to solve the problem. Now, I use ProcessBuilder to execute command.

private void executeCommand(String[] args) {
    ProcessBuilder pb = new ProcessBuilder(args);
    Process pc;
    try {
        pc = pb.start();
    } catch (Exception e) {


private void captureScreenshot() {
    executeCommand(new String[] { "adb", "-s", deviceSerialNo, "shell",
            "screencap", "-p", "/sdcard/" + screenshotFileName });
    executeCommand(new String[] { "adb", "-s", deviceSerialNo, "pull",
            "/sdcard/" + screenshotFileName, screenshotFilePath });
    executeCommand(new String[] { "adb", "-s", deviceSerialNo, "shell",
            "rm", "/sdcard/" + screenshotFileName });

It might because theses commands spend a long time to execute, so they need to wait for the previous one to finish, but I’m not sure. So if you know about this, leave your comment.