在使用uiautomator自动化测试框架过程中,基于对控件实现长按,发现uiautomator自带的方法longClick()很多时候不能实现对控件的长按,因此需要重写该方法。 主要代码如下: public static boolean longClickWithTime(UiObject obj, long time) throws Exception { Class<?> InteractionControllerClass = null; Method findAccessibilityNodeInfoMethod = null; Method getInteractionControllerMethod = null; Method touchDownMethod = null; Method touchUpMethod = null; Field WAIT_FOR_SELECTOR_TIMEOUT = null; findAccessibilityNodeInfoMethod = UiObject.class.getDeclaredMethod("findAccessibilityNodeInfo",long.class); findAccessibilityNodeInfoMethod.setAccessible(true); WAIT_FOR_SELECTOR_TIMEOUT = UiObject.class.getDeclaredField("WAIT_FOR_SELECTOR_TIMEOUT"); WAIT_FOR_SELECTOR_TIMEOUT.setAccessible(true); AccessibilityNodeInfo node = (AccessibilityNodeInfo) findAccessibilityNodeInfoMethod.invoke(obj, WAIT_FOR_SELECTOR_TIMEOUT.getLong(obj)); if(node == null) { throw new UiObjectNotFoundException(obj.getSelector().toString()); } Rect rect = obj.getVisibleBounds(); getInteractionControllerMethod = UiObject.class.getDeclaredMethod("getInteractionController"); getInteractionControllerMethod.setAccessible(true); Object interactionController = getInteractionControllerMethod.invoke(obj); InteractionControllerClass = Class.forName("com.android.uiautomator.core.InteractionController"); touchDownMethod = InteractionControllerClass.getDeclaredMethod("touchDown", int.class, int.class); touchDownMethod.setAccessible(true); touchUpMethod = InteractionControllerClass.getDeclaredMethod("touchUp", int.class, int.class); touchUpMethod.setAccessible(true); if(Boolean.parseBoolean(touchDownMethod.invoke(interactionController, rect.centerX(), rect.centerY()).toString())) { SystemClock.sleep(time); if(Boolean.parseBoolean(touchUpMethod.invoke(interactionController, rect.centerX(), rect.centerY()).toString())) { return true; } } return false; } 调用方式: 在使用uiautomator自动化框架时,调用longClickWithTime(Object, time)方法来实现对UiObject控件长按效果。其中Object参数:uiautomator UiObject控件对象,time:表示长按时间,单位为毫秒。 例如:对手机主页时钟按钮进行长按5s操作, longClickWithTime(new UiCollection(new UiObject(new UiSelector().text("Clock")), 5000);