Skip to content

Instantly share code, notes, and snippets.

@KenVanHoeylandt
Last active April 5, 2016 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KenVanHoeylandt/94c4389e9b210f0ec807790df8b90422 to your computer and use it in GitHub Desktop.
Save KenVanHoeylandt/94c4389e9b210f0ec807790df8b90422 to your computer and use it in GitHub Desktop.
DisableAnimationsRule
task grantAnimationPermission(type: Exec, dependsOn: 'installDebug') {
commandLine "adb shell pm grant com.my.app.id android.permission.SET_ANIMATION_SCALE".split(' ')
}
tasks.whenTaskAdded { task ->
if (task.name.startsWith('connected')) {
task.dependsOn grantAnimationPermission
}
}
// Source: http://product.reverb.com/2015/06/06/disabling-animations-in-espresso-for-android-testing/
public class DisableAnimationsRule implements TestRule {
private Method mSetAnimationScalesMethod;
private Method mGetAnimationScalesMethod;
private Object mWindowManagerObject;
public DisableAnimationsRule() {
try {
Class<?> windowManagerStubClazz = Class.forName("android.view.IWindowManager$Stub");
Method asInterface = windowManagerStubClazz.getDeclaredMethod("asInterface", IBinder.class);
Class<?> serviceManagerClazz = Class.forName("android.os.ServiceManager");
Method getService = serviceManagerClazz.getDeclaredMethod("getService", String.class);
Class<?> windowManagerClazz = Class.forName("android.view.IWindowManager");
mSetAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("setAnimationScales", float[].class);
mGetAnimationScalesMethod = windowManagerClazz.getDeclaredMethod("getAnimationScales");
IBinder windowManagerBinder = (IBinder) getService.invoke(null, "window");
mWindowManagerObject = asInterface.invoke(null, windowManagerBinder);
}
catch (Exception e) {
throw new RuntimeException("Failed to access animation methods", e);
}
}
@Override
public Statement apply(final Statement statement, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
setAnimationScaleFactors(0.0f);
try { statement.evaluate(); }
finally { setAnimationScaleFactors(1.0f); }
}
};
}
private void setAnimationScaleFactors(float scaleFactor) throws Exception {
float[] scaleFactors = (float[]) mGetAnimationScalesMethod.invoke(mWindowManagerObject);
Arrays.fill(scaleFactors, scaleFactor);
mSetAnimationScalesMethod.invoke(mWindowManagerObject, scaleFactors);
}
}
@ClassRule
public static DisableAnimationsRule disableAnimationsRule = new DisableAnimationsRule();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment