Skip to content

Instantly share code, notes, and snippets.

@Peddro
Last active February 23, 2016 11:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Peddro/1d6cafc72a9d77c274b7 to your computer and use it in GitHub Desktop.
Save Peddro/1d6cafc72a9d77c274b7 to your computer and use it in GitHub Desktop.
Helper for screengrab to take delayed screenshots
public class ScreengrabHelper {
private static ScreengrabHelper instance;
private static final long INIT_DELAY = 2000;
private long delay;
private boolean screenShotTaken;
public ScreengrabHelper() {
this.delay = INIT_DELAY;
}
public static void delayScreenshot(String name) {
ensureInstance();
instance.takeDelayScreenshot(name);
}
private static void ensureInstance() {
if (instance == null) {
instance = new ScreengrabHelper();
}
}
private void takeDelayScreenshot(String name) {
screenShotTaken = false;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
screenShotTaken = true;
}
}, delay);
new Wait(new Wait.Condition() {
@Override
public boolean check() {
return screenShotTaken;
}
}).waitForIt();
Screengrab.screenshot(name);
}
public static void setDelay(long delay) {
ensureInstance();
instance.changeDelay(delay);
}
public void changeDelay(long delay) {
this.delay = delay;
}
}
public class Wait {
private static final int CHECK_INTERVAL = 100;
private static final int TIMEOUT = 10000;
public interface Condition {
boolean check();
}
private Condition mCondition;
public Wait(Condition condition) {
mCondition = condition;
}
public void waitForIt() {
boolean state = mCondition.check();
long startTime = System.currentTimeMillis();
while (!state) {
try {
Thread.sleep(CHECK_INTERVAL);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (System.currentTimeMillis() - startTime > TIMEOUT) {
throw new AssertionError("Wait timeout.");
}
state = mCondition.check();
}
}
}
@Peddro
Copy link
Author

Peddro commented Feb 23, 2016

Usage:
ScreengrabHelper.delayScreenshot("screenshot_name");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment