Android UI Test Screenshot

Target

在Android UI Test時,想要screenshot去記錄當時的畫面,
主要介紹有哪些方式可以實作出來。

Action Items

  • Solution 1: View drawing cache
  • Solution 2: Use screengrab (library)
  • Solution 3: Use FalconSpoon (library)

Quick Start

Solution 1: View drawing cache

Step 1: screenshot function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

public static void takeScreenshot(String name, Activity activity) {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/" + name +".jpg";

View view = activity.getWindow().getDecorView().getRootView();
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);

OutputStream outputStream = null;
File imageFile = new File(path);
try {
outputStream = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {

if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
  • Setup view’s drawing cache
  • Drawing cache convert to Bitmap
  • Save file with Bitmap

Step 2: Setup permission

1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Comment

當擷取畫面需要包含 dialog 元件時,需要額外取得 dialog 元件,
並且透過 Canvas ,將 Activity View 與 dialog View 合併起來。

Solution 2: Use screengrab (library)

Step 1: Gradle dependency

build.gradle(Module: Application) -> dependencies

1
androidTestCompile 'tools.fastlane:screengrab:0.2.0'

Step 2: Example

Test is file name.

1
Screengrab.screenshot("Test");

Comment

可以截取畫面,但是 dialog 無法截取。

Solution 3: Use FalconSpoon (library)

Step 1: Gradle dependency

build.fradle(Module: Application) -> dependencies

1
androidTestCompile 'com.jraska:falcon-spoon-compat:1.0.1'

Step 2: Example

tag include file name.

1
FalconSpoon.screenshot(activity, tag);

Comment

可以截取畫面,畫面中可包含 dialog。

Reference

  1. http://stackoverflow.com/questions/28571185/what-is-the-simplest-way-to-create-a-ui-test-in-android-studio-that-can-take-scr
  2. http://gold.xitu.io/entry/56c2f5961532bc0054b39882
  3. https://github.com/jraska/Falcon
文章目录
  1. 1. Target
  2. 2. Action Items
  3. 3. Quick Start
    1. 3.1. Solution 1: View drawing cache
      1. 3.1.1. Step 1: screenshot function
      2. 3.1.2. Step 2: Setup permission
      3. 3.1.3. Comment
    2. 3.2. Solution 2: Use screengrab (library)
      1. 3.2.1. Step 1: Gradle dependency
      2. 3.2.2. Step 2: Example
      3. 3.2.3. Comment
    3. 3.3. Solution 3: Use FalconSpoon (library)
      1. 3.3.1. Step 1: Gradle dependency
      2. 3.3.2. Step 2: Example
      3. 3.3.3. Comment
  4. 4. Reference
,