Jing Li
Jing Li

Reputation: 15116

Why Android uiautomator's UiDevice#takeScreenshot always return false on emulator

When using uiautomator, takeScreenshot(File storePath) always returns false no matter what parameter I pass in.

I've tried to give either new File(dir_name, file_name) or new File(file_name), neither of them works (of course mkdir first if the dir_name doesn't exist).

Every time it just return false and /data/local/tmp/ on emulator is empty.

BTW, I don't think it's a permission problem, since trying the similar dumpWindowHierarchy could generate a dump file there.

Thanks in advance for your help.

Upvotes: 7

Views: 6620

Answers (2)

Rajesh
Rajesh

Reputation: 4769

The takeScreenshot() method is applicable from 4.2 and above android version devices

If the device version is appropriate, then use the following piece of code

File path = new File("/sdcard/filename.png");
    int SDK_VERSION = android.os.Build.VERSION.SDK_INT; 
    if (SDK_VERSION >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mUiAutomatorTestCase.getUiDevice().takeScreenshot(PATH);
    }

We can view the file by following command

$ adb shell ls -l /sdcard/name-of-file

Upvotes: 3

RKI
RKI

Reputation: 1969

If you are using emulator to run the tests you should turn on "Use Host GPU" in your AVD configuration. After this change it worked for me.

If you still got a problem you may try screencap. It is command line tool for taking screenshots. It works in both emulator settings. To save screenshot in given path execute:

Process process = Runtime.getRuntime().exec("screencap <path>");
process.waitFor();

Use /data/local/tmp to avoid problems with permission. You can use SD Card dir as well. It is asynchronous so wait until process is finished with waitFor(). It will recognize desired output format by extension of provided file.

Or you can get PNG in InputStream (no need to wait):

Process process = Runtime.getRuntime().exec("screencap -p");
InputStream output = new BufferedInputStream(process.getInputStream());

You can omit -p if you wish to get file in JPEG. They JPEG screenshots are bigger, but it takes less time to get them.

Upvotes: 7

Related Questions