Skip to content

Instantly share code, notes, and snippets.

@paulo-raca
Created August 26, 2019 15:09
Show Gist options
  • Save paulo-raca/519e63a305ac45d103e72fdee1208dfe to your computer and use it in GitHub Desktop.
Save paulo-raca/519e63a305ac45d103e72fdee1208dfe to your computer and use it in GitHub Desktop.
package com.crowdstrike.android.playstorecontroller.util;
import android.Manifest;
import android.app.ActivityThread;
import android.app.Instrumentation;
import android.app.UiAutomation;
import android.graphics.Bitmap;
import android.nfc.Tag;
import android.os.Build;
import android.os.Debug;
import android.os.Environment;
import android.os.Process;
import android.util.Log;
import androidx.test.uiautomator.UiDevice;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class ScreenshotUtil {
private static final String TAG = ScreenshotUtil.class.getSimpleName();
private static Instrumentation sInstrumentation = ActivityThread.currentActivityThread().getInstrumentation();
private static DateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
private static File sScreenshotDir;
static {
sDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
sInstrumentation.getUiAutomation().grantRuntimePermission(
sInstrumentation.getTargetContext().getPackageName(),
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Process.myUserHandle());
sInstrumentation.getUiAutomation().grantRuntimePermission(
sInstrumentation.getTargetContext().getPackageName(),
Manifest.permission.READ_EXTERNAL_STORAGE,
Process.myUserHandle());
} catch (Throwable t) {
Log.w(TAG, "Cannot grant EXTERNAL_STORAGE permissions", t);
}
sScreenshotDir = new File(Environment.getExternalStorageDirectory(), "test-screenshots");
sScreenshotDir.mkdirs();
}
public static void takeScreenshot(String name) {
File f = new File(sScreenshotDir, sDateFormat.format(new Date()) + "-" + name + ".png");
try {
boolean taken = UiDevice.getInstance(sInstrumentation).takeScreenshot(f);
if (taken) {
Log.i(TAG, "Taken Screenshot: " + f);
} else {
Log.w(TAG, "Failed to take screenshot: " + f);
}
} catch (Throwable t) {
Log.w(TAG, "Failed to take screenshot: " + f, t);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment